entx

package module
v0.38.8 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 27 Imported by: 8 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Build status Quality Gate Status Go Reference

entx

A helper package for working with ent, which includes the following high-level utilities:

  • Mixin used for assigning a different ID type than the one generated by ent (we use ULIDs)
  • Mixin used for assigning some default columns (created_at, created_by, etc. - check out the mixin directory for more details)
  • A vanilla, drop-in, setup for using ent with our standard tool chains gqlgen, gqlgenc, and some other helpers
  • Soft-delete extension with cascade delete functionality added in
  • Multi-driver support for various databases
  • SQLite connection interface management
  • Annotating schemas with product modules and generating a feature map (see this README section)

enthistory

enthistory is a powerful extension for generating history tables using ent - the plugin will add-on to your existing entc usage and enumerate over your current schemas to create new "history" schemas containing an inventory of the changes related to the existing tables.

Credit to flume/enthistory for the inspiration - we chose to create our own for a number of reasons, some being:

  • We have existing patterns within the theopenlane/core repo which would today require an import of the entx package and likely be a non-starter for the original authors
  • We have more complex schemas, mixins, code gen usage; when attempting to use the originally developed plugin we ran into numerous problems based on the types / methods we had already chosen and was easier to short-term directly update with the changes we needed
  • integration with and/or mutual code updates for our "soft delete" constructs to continue to function
  • Specific desires / levels of control regarding data retention and tracking
  • Authorization policies specific to using openFGA may be harder for others to adopt
Installation

You can install enthistory by running the following command:

go get github.com/theopenlane/entx/history@latest

In addition to installing enthistory, you need to already have, or create two files (entc.go and generate.go) - this can be within your ent directory, but full instructions can be found in the upstream godoc documentation. The entc.go file should reference the ent history plugin via enthistory.New, and the options you include for the plugin depend on your desired implementation (see the Configuration section below) but you can use the following example for reference:

//go:build ignore

package main

import (
    "log"
    "github.com/theopenlane/entx/history"
    "entgo.io/ent/entc"
)

func main() {
    // create new extension with options
    historyExt := enthistory.New(
        enthistory.WithAuditing(),
    )

    // generate the history schemas
    if err := historyExt.GenerateSchemas(); err != nil {
        log.Fatalf("generating history schema: %v", err)
    }

    // run ent generate with extension for other templates
    if err := entc.Generate("./schema",
        &gen.Config{},
        entc.Extensions(
            historyExt,
        ),
    ); err != nil {
        log.Fatal("running ent codegen:", err)
    }
}

Be sure to read the upstream ent documentation describing the differences between entc and ent, but assuming you're using entc as a package you would want the minimum reference to the run the code generate processes with entc command like below:

package ent

//go:generate go run -mod=mod entc.go

You can additionally call other packages such as mockery within your generate.go - the core repo could be a good reference point for this.

Usage
Querying History

After generating your history tables from your schema, you can use the ent client to query the history tables. The generated code automatically creates history tables for every table in your schema and hooks them up to the ent client.

You can query the history tables directly, just like any other ent table. You can also retrieve the history of a specific row using the History() method.

enthistory tracks the user who updates a row if you provide a key during initialization. You can store a user's ID, email, IP address, etc., in the context with the key you provide to track it in the history.

Here's an example that demonstrates these features:

// Create
client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&_fk=1")
// Activate the history hooks on the client
client.WithHistory()
character, _ := client.Character.Create().SetName("Marceline").Save(ctx)
characterHistory, _ := character.History().All(ctx)
fmt.Println(len(characterHistory)) // 1

// Update
character, _ = character.Update().SetName("Marshall Lee").Save(ctx)
characterHistory, _ = character.History().All(ctx)
fmt.Println(len(characterHistory)) // 2

// Delete
client.Character.DeleteOne(character)
characterHistory, _ = character.History().All(ctx)
fmt.Println(len(characterHistory)) // 3

In addition to regular queries, you can perform common history queries such as retrieving the earliest history, the latest history, and the history of a row at a specific point in time. enthistory provides functions for these queries:

character, _ := client.Character.Query().First(ctx)

// Get the earliest history for this character (i.e., when the character was created)
earliest, _ := character.History().Earliest(ctx)

// Get the latest history for this character (i.e., the current state of the actual character)
latest, _ := character.History().Latest(ctx)

// Get the history for this character as it was at a given point in time
// (i.e., the state of the actual character at the given point in time)
historyNow, _ := character.History().AsOf(ctx, time.Now())

You can also use the .Next() and .Prev() methods to navigate to the next or previous history entries in time:

character, _ := client.Character.Query().First(ctx)

// Get the earliest history for this character (i.e., when the character was created)
earliest, _ := character.History().Earliest(ctx)

// Get the next history after the earliest history
next, _ := earliest.Next(ctx)

// Get the previous history before the next history
prev, _ := next.Prev(ctx)

// prev would now be the earliest history once again
fmt.Println(prev.ID == earliest.ID) // true
Restoring History

If you need to rollback a row in the database to a specific history entry, you can use the .Restore() function to accomplish that. NOTE: do not attempt to do this in your production environment or otherwise without testing in advance and creating your own SOP's around these types of procedures. By rolling back you are effectively overwriting your primary data source with a new entry, so use with caution!

Here's an example:

// Let's say we create this character
simon, _ := client.Character.Create().SetName("Simon Petrikov").Save(ctx)
// And we update the character's name
iceking, _ := simon.Update().SetName("Ice King").Save(ctx)
// We can find the exact point in history we want to restore, in this case, the oldest history entry
icekingHistory, _ := iceking.History().Order(ent.Asc(characterhistory.FieldHistoryTime)).First(ctx)
// And we can restore the value back to the original table
restored, _ = icekingHistory.Restore(ctx)

fmt.Println(simon.ID == restored.ID) // true
fmt.Println(simon.Name == restored.Name) // true
// The restoration is also tracked in history
simonHistory, _ := restored.History().All(ctx)
fmt.Println(len(simonHistory)) // 3
Auditing

enthistory includes tools for "auditing" history tables by providing a means of exporting the data inside of them. You can enable auditing by using the enthistory.WithAuditing() option when initializing the extension. The main tool for auditing is the Audit() method, which builds an audit log of the history tables that you can export as a file, upload to S3, or inspect.

Here's an example of how to use the Audit() method to export an audit log as a CSV file:

auditTable, _ := client.Audit(ctx)

The audit log contains six columns when user tracking is enabled. Here's an example of how the audit log might look:

Table Ref Id History Time Operation Changes Updated By
CharacterHistory 1 Sat Mar 18 16:31:31 2023 INSERT age: 47 name: "Simon Petrikov" 75
CharacterHistory 1 Sat Mar 18 16:31:31 2023 UPDATE name: "Simon Petrikov" -> "Ice King" 75
CharacterHistory 1 Sat Mar 18 16:31:31 2023 DELETE age: 47 name: "Ice King" 75

You can also build your own custom audit log using the .Diff() method on history models. The Diff() method returns the older history, the newer history, and the changes to fields when comparing the newer history to the older history.

Configuration Options

enthistory provides several configuration options to customize its behavior.

Immutable Tracked Fields

History rows are insert only: they are written once by the mutation hook and never updated. Every tracked field copied from your original table is therefore generated as Immutable, and any UpdateDefault on a copied field is cleared so a snapshot column keeps the value it was written with. This removes the update builders for the history types entirely.

History Time Indexing

By default, an index is not placed on the history_time field. If you want to enable indexing on the history_time field, you can use the enthistory.WithHistoryTimeIndex() configuration option. This option gives you more control over indexing based on your specific needs.

Updated By

To track which users are making changes to your tables, you can use the enthistory.WithUpdatedBy() option when initializing the extension. You need to provide a key name (string) and specify the type of value (enthistory.ValueTypeInt for integers or enthistory.ValueTypeString for strings). The value corresponding to the key should be stored in the context using context.WithValue(). If you don't plan to use this feature, you can omit - you may also already have an existing audit mixin or similar which tracks the user performing the action, in which case, these fields would already be contained within the created history tables.

// Example for tracking user ID
enthistory.WithUpdatedBy("userId", enthistory.ValueTypeInt)

// Example for tracking user email
enthistory.WithUpdatedBy("userEmail", enthistory.ValueTypeString)
Deleted By

To track which users are making changes to your tables, you can use the enthistory.WithDeletedBy() option when initializing the extension. You need to provide a key name (string) and specify the type of value (enthistory.ValueTypeInt for integers or enthistory.ValueTypeString for strings). The value corresponding to the key should be stored in the context using context.WithValue(). If you don't plan to use this feature, you can omit it.

// Example for tracking user ID
enthistory.WithDeletedBy("userId", enthistory.ValueTypeInt)

// Example for tracking user email
enthistory.WithDeletedBy("userEmail", enthistory.ValueTypeString)
Auditing

As mentioned earlier, you can enable auditing by using the enthistory.WithAuditing() configuration option when initializing the extension.

Excluding History on a Schema

enthistory is designed to always track history, but in cases where you don't want to generate history tables for a particular schema, you can apply annotations to the schema to exclude it. Here's an example:

func (Character) Annotations() []schema.Annotation {
    return []schema.Annotation{
        enthistory.Annotations{
            // Exclude history tables for this schema
            Exclude: true,
        },
    }
}
Setting a Schema Path

If you want to set an alternative schema location other than ent/schema, you can use the enthistory.WithSchemaPath() configuration option. The schema path should be the same as the one set in the entc.Generate function. If you don't plan to set an alternative schema location, you can omit this option.

func main() {
    entc.Generate("./schema2",
        &gen.Config{},
        entc.Extensions(
            enthistory.NewHistoryExtension(
                enthistory.WithSchemaPath("./schema2")
            ),
        ),
    )
}

For a complete example of using a custom schema path, refer to the custompaths example.

Setting a Schema Name

If you want to set the schema name for entsql, you can use the enthistory.WithSchemaName() configuration option. This can be used in conjunction with ent Multiple Schema Migrations and the Schema Config features.

Adding GQL Query

If you are using gqlgen and want to generate the query resolvers for the history schemas, you can use the enthistory.WithGQLQuery() configuration option. With this enabled, ent.resolvers with be created, such as:

// TodoHistories is the resolver for the todoHistories field.
func (r *queryResolver) TodoHistories(ctx context.Context, after *entgql.Cursor[string], first *int, before *entgql.Cursor[string], last *int, orderBy *generated.TodoHistoryOrder, where *generated.OrganizationHistoryWhereInput) (*generated.TodoHistoryConnection, error) {
    panic(fmt.Errorf("not implemented: TodoHistories - todoHistories"))
}
Adding a Skipper Function

If you want to conditionally skip saving history data, you can use the enthistory.WithSkipper() configuration option. This should be the string representation that returns true or false. The function has access to the mutation object and the context. For example:

    skipper := `
        hasFeature := m.CheckFeature(ctx)

        return !hasFeature
    `

    historyExt := enthistory.NewHistoryExtension(
        enthistory.WithSkipper(skipper),
    )
Caveats

Here are a few caveats to keep in mind when using enthistory:

Edges

To track edges with history, you need to manage your own through tables. enthistory does not hook into the ent-generated through tables automatically, but managing through tables manually is straightforward. Note that if you use the setters for edges on the main schema tables, the history on the through tables won't be tracked. To track history on through tables, you must update the through tables directly with the required information.

Instead of using .AddFriends() like this:

finn, _ := client.Character.Create().SetName("Finn the Human").Save(ctx)
jake, _ := client.Character.Create().SetName("Jake the Dog").Save(ctx)
finn, _ = finn.Update().AddFriends(jake).Save(ctx)

You should use the Friendship through table:

finn, _ := client.Character.Create().SetName("Finn the Human").Save(ctx)
jake, _ := client.Character.Create().SetName("Jake the Dog").Save(ctx)
friendship, _ := client.Friendship.Create().SetCharacterID(finn.ID).SetFriendID(jake.ID).Save(ctx)

For more information on through tables and edges, refer to the ent documentation.

Enums

If your ent schemas contain enum fields, it is recommended to create Go enums and set the GoType on the enum field. This is because ent generates a unique enum type for both your schema and the history table schema, which may not work well together.

Instead of using .Values() like this:

field.Enum("action").
    Values("PUSH", "PULL")

Use .GoType() like this:

field.Enum("action").
    GoType(types.Action(""))

For more information on enums, refer to the ent documentation.

Exportable schemas

This package supports annotating ent schemas to allow the to be exported into multiple formats e.g csv and others Here is an example

func (Control) Annotations() []schema.Annotation {
 return []schema.Annotation{
  entx.Exportable{},
 }
}
Adding New Features

Adding a new feature is as simple as referencing a new identifier in your schema annotations. After updating your schemas, run code generation again and the feature map will contain the new module.

Contributing

Please read the contributing guide.

Documentation

Overview

Package entx is a package of tools for interacting with ent

Index

Constants

View Source
const CatalogManagedDirectiveName = "catalogManaged"

CatalogManagedDirectiveName is the GraphQL directive on catalog-copied fields

View Source
const (
	DefaultCacheTTL = 1 * time.Second
)
View Source
const SkipQueryCheckForModuleAnnotationName = "OPENLANE_SKIP_QUERY_CHECK_FOR_MODULE"

Variables

View Source
var AnonymousFieldAnnotationName = "OPENLANE_ANONYMOUS_FIELD"

AnonymousFieldAnnotationName is the annotation name for a field anonymous callers may set in mutations

View Source
var ApprovalApproverAnnotationName = "OPENLANE_APPROVAL_APPROVER"

ApprovalApproverAnnotationName is the annotation name for a schema's approval-approver field

View Source
var ApprovalStatusAnnotationName = "OPENLANE_APPROVAL_STATUS"

ApprovalStatusAnnotationName is the annotation name for a schema's approval-status field

View Source
var BulkCreateAnnotationName = "OPENLANE_BULK_CREATE_METHOD"

BulkCreateAnnotationName is the annotation to determine if to sequentially create bulk items or use the bulk builders.

View Source
var CSVReferenceAnnotationName = "OPENLANE_CSV_REFERENCE"

CSVReferenceAnnotationName is the annotation name for CSV reference field mappings

View Source
var CascadeAnnotationName = "OPENLANE_CASCADE"

CascadeAnnotationName is a name for our cascading delete annotation

View Source
var CascadeThroughAnnotationName = "OPENLANE_CASCADE_THROUGH"

CascadeThroughAnnotationName is a name for our cascading through edge delete annotation

View Source
var CaseInsensitiveFieldAnnotationName = "OPENLANE_CASE_INSENSITIVE_FIELD"

CaseInsensitiveFieldAnnotationName is the annotation name for case-insensitive ingest change detection

View Source
var CatalogEdgeAnnotationName = "OPENLANE_CATALOG_EDGE"

CatalogEdgeAnnotationName is the annotation name for the self edge pointing at a schema's catalog row

View Source
var ConsoleRouteAnnotationName = "OPENLANE_CONSOLE_ROUTE"

ConsoleRouteAnnotationName is the annotation name for console routes on schemas

View Source
var DisplayNameAnnotationName = "OPENLANE_DISPLAY_NAME"

DisplayNameAnnotationName is the annotation name for a schema's display-name field

View Source
var (
	// ErrUnsupportedDialect is returned when an unsupported dialect is used
	ErrUnsupportedDialect = errors.New("unsupported dialect")
)
View Source
var FGACrudAnnotationName = "OPENLANE_FGA_CRUD_OPERATIONS"

FGACrudAnnotationName is the annotation name for crud operations

View Source
var FGACrudParentAnnotationName = "OPENLANE_FGA_PARENT_CRUD_OPERATIONS"

FGACrudParentAnnotationName is the annotation name for parent objects for crud operations

View Source
var FeatureVisibilityAnnotationName = "OPENLANE_SCHEMA_VISIBILITY"

FeatureVisibilityAnnotationName is the annotation name used to flag schema visibility

View Source
var FieldSourceManagedAnnotationName = "OPENLANE_FIELD_SOURCE_MANAGED"

FieldSourceManagedAnnotationName is the annotation name for fields whose value is owned by the upstream source

View Source
var FileCategoryAnnotationName = "OPENLANE_FILE_CATEGORY"

FileCategoryAnnotationName is the annotation name for default file categories.

View Source
var GroupPermissionsEnabledName = "OPENLANE_GROUP_PERMISSIONS_ENABLED"

GroupPermissionsEnabledName is the annotation name for group permissions enabled on the object

View Source
var IntegrationMappingFieldAnnotationName = "OPENLANE_INTEGRATION_MAPPING_FIELD"

IntegrationMappingFieldAnnotationName is the annotation name for integration mapping fields

View Source
var IntegrationMappingSchemaAnnotationName = "OPENLANE_INTEGRATION_MAPPING_SCHEMA"

IntegrationMappingSchemaAnnotationName is the annotation name for integration mapping schemas

View Source
var MatchAlternativeFieldAnnotationName = "OPENLANE_MATCH_ALTERNATIVE_FIELD"

MatchAlternativeFieldAnnotationName is the annotation name for extra columns a field's ingest lookup matches

View Source
var MentionSourceAnnotationName = "OPENLANE_MENTION_SOURCE"

MentionSourceAnnotationName is the annotation name for mention-scanned rich-text fields

View Source
var OrgOwnedSchemaName = "OPENLANE_ORG_OWNED_SCHEMA"

OrgOwnedSchemaName is the annotation name for org owned schemas

View Source
var QueryGenAnnotationName = "OPENLANE_QUERYGEN"

QueryGenAnnotationName is a name for our graphql query generation annotation

View Source
var SchemaGenAnnotationName = "OPENLANE_SCHEMAGEN"

SchemaGenAnnotationName is a name for our graphql schema generation annotation

View Source
var SearchFieldAnnotationName = "OPENLANE_SEARCH"

SearchFieldAnnotationName is a name for the search field annotation

View Source
var SnapshotRemovalAnnotationName = "OPENLANE_SNAPSHOT_REMOVAL"

SnapshotRemovalAnnotationName is the annotation name for a schema's removed_at-style field

View Source
var (

	// SoftDeleteTypeKey carries the schema type of an in-progress soft delete
	SoftDeleteTypeKey = contextx.NewKey[string]()
)
View Source
var SystemOwnedSchemaName = "OPENLANE_SYSTEM_OWNED_SCHEMA"

SystemOwnedSchemaName is the annotation name for org owned schemas

View Source
var TaskRuleAnnotationName = "OPENLANE_TASK_RULE"

TaskRuleAnnotationName is the annotation name for suggested-task generation rules

View Source
var WebhookPayloadFieldAnnotationName = "OPENLANE_WEBHOOK_PAYLOAD_FIELD"

WebhookPayloadFieldAnnotationName is the annotation name for fields to include in webhook payloads

View Source
var WorkflowEligibleAnnotationName = "OPENLANE_WORKFLOW_ELIGIBLE"

WorkflowEligibleAnnotationName is the annotation name for workflow-eligible fields

Functions

func CatalogManagedField added in v0.37.0

func CatalogManagedField() []schema.Annotation

CatalogManagedField marks a catalog-copied field and adds the @catalogManaged directive

func CheckEntDialect

func CheckEntDialect(d string) (string, error)

CheckEntDialect checks if the dialect is supported and returns the ent dialect corresponding to the given dialect

func CheckIsSoftDelete

func CheckIsSoftDelete(ctx context.Context) bool

CheckIsSoftDelete checks if the softDeleteKey is set in the context @deprecated use CheckIsSoftDeleteType with object type instead

func CheckIsSoftDeleteType added in v0.18.0

func CheckIsSoftDeleteType(ctx context.Context, objectType string) bool

CheckIsSoftDeleteType checks if the softDeleteKey is set in the context for the given object type

func CheckMultiwriteSupport

func CheckMultiwriteSupport(d string) bool

CheckMultiwriteSupport checks if the dialect supports multiwrite

func CheckSkipSoftDelete

func CheckSkipSoftDelete(ctx context.Context) bool

CheckSkipSoftDelete checks whether soft-delete skipping was requested.

func DecodeAnnotation added in v0.29.0

func DecodeAnnotation(annotation any, target any) error

DecodeAnnotation is a common wrapper to decode an annotation with json marshal and unmarshal into the target

func GetAnnotation added in v0.29.0

func GetAnnotation[T DecodableAnnotation, K any](t K) (T, bool)

GetAnnotation returns the decoded annotation of type T if present on the node. T must be a pointer type, e.g. GetAnnotation[*MyAnnotation](node).

func HasAnnotation added in v0.29.0

func HasAnnotation[T schema.Annotation, K any](t K) bool

HasAnnotation returns true if the type has the provided annotation type

func Healthcheck

func Healthcheck(client *entsql.Driver) func(ctx context.Context) error

Healthcheck pings the DB to check if the connection is working

func IsSoftDelete

func IsSoftDelete(parent context.Context, objectType string) context.Context

IsSoftDelete returns a new context that informs the delete is a soft-delete for interceptor/hooks.

func MarshalRawMessage

func MarshalRawMessage(t json.RawMessage) graphql.Marshaler

MarshalRawMessage provides a graphql.Marshaler for json.RawMessage

func SkipSoftDelete

func SkipSoftDelete(parent context.Context) context.Context

SkipSoftDelete returns a new context that skips the soft-delete interceptor/hooks.

func UnmarshalRawMessage

func UnmarshalRawMessage(v any) (json.RawMessage, error)

UnmarshalRawMessage provides a graphql.Unmarshaler for json.RawMessage

Types

type AnonymousFieldAnnotation added in v0.36.2

type AnonymousFieldAnnotation struct{}

AnonymousFieldAnnotation marks a field anonymous callers may set in create and update mutations, every other mutation input field is rejected for anonymous callers

func AnonymousField added in v0.36.2

func AnonymousField() AnonymousFieldAnnotation

AnonymousField marks a field anonymous callers may set in create and update mutations

func (AnonymousFieldAnnotation) Name added in v0.36.2

Name returns the name of the AnonymousFieldAnnotation

type ApprovalApproverAnnotation added in v0.32.0

type ApprovalApproverAnnotation struct{}

ApprovalApproverAnnotation marks the group-id field resolving a schema's approvers

func ApprovalApprover added in v0.32.0

func ApprovalApprover() ApprovalApproverAnnotation

ApprovalApprover marks the group-id field resolving a schema's approvers

func (ApprovalApproverAnnotation) Name added in v0.32.0

Name returns the name of the ApprovalApproverAnnotation

type ApprovalStatusAnnotation added in v0.32.0

type ApprovalStatusAnnotation struct{}

ApprovalStatusAnnotation marks the enum field carrying a schema's approval status

func ApprovalStatus added in v0.32.0

func ApprovalStatus() ApprovalStatusAnnotation

ApprovalStatus marks the enum field carrying a schema's approval status

func (ApprovalStatusAnnotation) Name added in v0.32.0

Name returns the name of the ApprovalStatusAnnotation

type BulkCreateMethodAnnotation added in v0.36.0

type BulkCreateMethodAnnotation struct {
	Sequential bool
}

BulkCreateMethodAnnotation controls how bulk create helpers create records. if Sequential is true, it will preserve the values returned by the hooks ( if any ) instead of calling the bulk builders. this is useful for certain bulk creations that need to update existing records like invitations and others.

func SequentialBulkCreate added in v0.36.0

func SequentialBulkCreate() *BulkCreateMethodAnnotation

SequentialBulkCreate instructs the resolver to sequentially create the items so we can handle cases where we want to handle existing values in the db.

func (*BulkCreateMethodAnnotation) Decode added in v0.36.0

func (a *BulkCreateMethodAnnotation) Decode(annotation any) error

Decode unmarshalls the BulkCreateMethodAnnotation

func (BulkCreateMethodAnnotation) Name added in v0.36.0

Name returns the annotation name

type CSVRefBuilder added in v0.22.0

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

CSVRefBuilder provides a fluent interface for building CSVReferenceAnnotation. All lookups are automatically scoped to the organization context from the request. The target entity is inferred from the edge associated with the annotated ID field. Use TargetEntity() only when no edge exists.

Example - annotate a user_id field to be populated from CSV email column:

field.String("assigned_to_user_id").
    Annotations(
        entx.CSVRef().
            FromColumn("AssignedToEmail").
            MatchOn("email"),
    )

Example - annotate a group_ids field:

field.Strings("blocked_group_ids").
    Annotations(
        entx.CSVRef().
            FromColumn("BlockedGroupNames").
            MatchOn("name"),
    )

Example - specify target entity when no edge exists:

field.String("control_id").
    Annotations(
        entx.CSVRef().
            FromColumn("ControlRefCode").
            MatchOn("ref_code").
            TargetEntity("Control"),
    )

func CSVRef added in v0.22.0

func CSVRef() *CSVRefBuilder

CSVRef starts building a CSV reference annotation Place this annotation on ID fields that should be populated from friendly CSV values

func (*CSVRefBuilder) CreateChild added in v0.38.3

func (b *CSVRefBuilder) CreateChild(field string) *CSVRefBuilder

CreateChild creates a new record on the annotated edge for each non-empty cell, setting field to the cell value and linking it to the row's entity, e.g. CSVRef().FromColumn("Comment").CreateChild("text") on a comments edge

func (*CSVRefBuilder) CreateIfMissing added in v0.22.0

func (b *CSVRefBuilder) CreateIfMissing() *CSVRefBuilder

CreateIfMissing enables auto-creation of missing records during CSV import only for entities where auto-creation makes sense

func (*CSVRefBuilder) FromColumn added in v0.22.0

func (b *CSVRefBuilder) FromColumn(csvColumn string) *CSVRefBuilder

FromColumn sets the CSV column header that users will see and provide values in For example, "AssignedToEmail" means the CSV will have a column with that header

func (*CSVRefBuilder) MarshalJSON added in v0.22.0

func (b *CSVRefBuilder) MarshalJSON() ([]byte, error)

MarshalJSON serializes the builder as the underlying CSVReferenceAnnotation. This ensures ent stores the annotation in the expected format for decoding.

func (*CSVRefBuilder) MatchOn added in v0.22.0

func (b *CSVRefBuilder) MatchOn(field string) *CSVRefBuilder

MatchOn sets the field on the target entity to match against when resolving friendly CSV values to IDs. Common values: email, name, ref_code, slug.

func (*CSVRefBuilder) Name added in v0.22.0

func (b *CSVRefBuilder) Name() string

Name returns the annotation name, implementing the ent Annotation interface

func (*CSVRefBuilder) TargetEntity added in v0.22.0

func (b *CSVRefBuilder) TargetEntity(entity string) *CSVRefBuilder

TargetEntity explicitly sets the target entity type for lookups. Only needed when the target cannot be inferred from an edge definition.

type CSVReferenceAnnotation added in v0.22.0

type CSVReferenceAnnotation struct {
	// CSVColumn is the friendly CSV header name that users will see (e.g., AssignedToUserEmail)
	CSVColumn string
	// MatchField is the field on the target entity to match against (e.g., email, name, ref_code)
	MatchField string
	// TargetEntity optionally specifies the target entity type when it cannot be inferred from edges
	TargetEntity string
	// CreateIfMissing allows auto-creation of missing records during CSV import (e.g., platforms)
	CreateIfMissing bool
	// ChildField is the string field on the edge's target entity set from the column, creating one linked child per row
	ChildField string
}

CSVReferenceAnnotation is an annotation used to map CSV columns to ID fields via lookups All lookups are automatically scoped to the organization context from the request.

func (*CSVReferenceAnnotation) Decode added in v0.22.0

func (a *CSVReferenceAnnotation) Decode(annotation any) error

Decode unmarshalls the CSVReferenceAnnotation

func (CSVReferenceAnnotation) Name added in v0.22.0

func (a CSVReferenceAnnotation) Name() string

Name returns the name of the CSVReferenceAnnotation

type CascadeAnnotation

type CascadeAnnotation struct {
	Field string
}

CascadeAnnotation is an annotation used to indicate that an edge should be cascaded

func CascadeAnnotationField

func CascadeAnnotationField(fieldname string) *CascadeAnnotation

CascadeAnnotationField sets the field name of the edge containing the ID of a record from the current schema

func (*CascadeAnnotation) Decode

func (a *CascadeAnnotation) Decode(annotation any) error

Decode unmarshalls the CascadeAnnotation

func (CascadeAnnotation) Name

func (a CascadeAnnotation) Name() string

Name returns the name of the CascadeAnnotation

type CascadeThroughAnnotation

type CascadeThroughAnnotation struct {
	Schemas []ThroughCleanup
}

CascadeThroughAnnotation is an annotation used to indicate that an edge should be cascaded through

func CascadeThroughAnnotationField

func CascadeThroughAnnotationField(schemas []ThroughCleanup) *CascadeThroughAnnotation

CascadeThroughAnnotationField sets the field name of the edge containing the ID of a record from the current schema

func (*CascadeThroughAnnotation) Decode

func (a *CascadeThroughAnnotation) Decode(annotation any) error

Decode unmarshalls the CascadeThroughAnnotation

func (CascadeThroughAnnotation) Name

Name returns the name of the CascadeThroughAnnotation

type CaseInsensitiveFieldAnnotation added in v0.34.0

type CaseInsensitiveFieldAnnotation struct {
	// CaseInsensitive compares the field case-insensitively in ingest change detection
	CaseInsensitive bool
}

CaseInsensitiveFieldAnnotation marks a field compared case-insensitively in ingest change detection

func FieldCaseInsensitive added in v0.34.0

func FieldCaseInsensitive() *CaseInsensitiveFieldAnnotation

FieldCaseInsensitive returns a new CaseInsensitiveFieldAnnotation with the flag set

func (*CaseInsensitiveFieldAnnotation) Decode added in v0.34.0

func (a *CaseInsensitiveFieldAnnotation) Decode(annotation any) error

Decode unmarshalls the CaseInsensitiveFieldAnnotation

func (CaseInsensitiveFieldAnnotation) Name added in v0.34.0

Name returns the name of the CaseInsensitiveFieldAnnotation

type CatalogEdgeAnnotation added in v0.35.0

type CatalogEdgeAnnotation struct{}

CatalogEdgeAnnotation marks the unique self edge whose foreign key points at the catalog row

func (CatalogEdgeAnnotation) Name added in v0.35.0

func (a CatalogEdgeAnnotation) Name() string

Name returns the name of the CatalogEdgeAnnotation

type CatalogEdgeBuilder added in v0.35.0

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

CatalogEdgeBuilder provides a fluent interface for CatalogEdgeAnnotation

func CatalogEdge added in v0.35.0

func CatalogEdge() *CatalogEdgeBuilder

CatalogEdge marks the unique self edge whose foreign key points at the catalog row

func (*CatalogEdgeBuilder) MarshalJSON added in v0.35.0

func (b *CatalogEdgeBuilder) MarshalJSON() ([]byte, error)

MarshalJSON serializes the builder as the underlying CatalogEdgeAnnotation

func (*CatalogEdgeBuilder) Name added in v0.35.0

func (b *CatalogEdgeBuilder) Name() string

Name returns the annotation name, implementing the ent Annotation interface

type Config

type Config struct {
	// Debug to print debug database logs
	Debug bool `json:"debug" koanf:"debug" jsonschema:"description=debug enables printing the debug database logs" default:"false"`
	// DatabaseName is the name of the database to use with otel tracing
	DatabaseName string `` /* 134-byte string literal not displayed */
	// DriverName name from dialect.Driver
	DriverName string `` /* 167-byte string literal not displayed */
	// MultiWrite enabled writing to two databases simultaneously
	MultiWrite bool `json:"multiwrite" koanf:"multiwrite" jsonschema:"description=enables writing to two databases simultaneously" default:"false"`
	// PrimaryDBSource is the primary database source for all read and write operations
	PrimaryDBSource string `` /* 198-byte string literal not displayed */
	// SecondaryDBSource for when multi write is enabled
	SecondaryDBSource string `` /* 231-byte string literal not displayed */
	// CacheTTL to have results cached for subsequent requests
	CacheTTL time.Duration `json:"cachettl" koanf:"cachettl" jsonschema:"description=cache results for subsequent requests, defaults to 1s" default:"1s"`
	// RunMigrations to run migrations on startup
	RunMigrations bool `json:"runmigrations" koanf:"runmigrations" jsonschema:"description=run migrations on startup" default:"true"`
	// MigrationProvider to use for running migrations
	MigrationProvider string `` /* 140-byte string literal not displayed */
	// EnableHistory to enable history data to be logged to the database
	EnableHistory bool `` /* 132-byte string literal not displayed */
	// MaxConnections is the maximum number of connections to the database
	MaxConnections int `` /* 127-byte string literal not displayed */
	// MaxIdleConnections is the maximum number of idle connections to the database
	MaxIdleConnections int `` /* 140-byte string literal not displayed */
}

Config Settings for the ent database client

type ConsoleRouteAnnotation added in v0.31.0

type ConsoleRouteAnnotation struct {
	// Base is the console landing path for the schema (e.g. "automation/tasks")
	Base string
	// IDParam routes object links through a query parameter (base?<IDParam>=<id>) instead
	// of a path segment
	IDParam string
	// Suffix is a path segment appended after the object ID (e.g. "view"); mutually
	// exclusive with IDParam
	Suffix string
}

ConsoleRouteAnnotation declares how console URLs are built for a schema's objects. Every unset field falls back to convention: Base defaults to the schema's plural table name and object IDs default to a path segment. The annotation's presence also opts a schema into route generation when it is outside the entity-operations registry

func ConsoleRoute added in v0.31.0

func ConsoleRoute(opts ...ConsoleRouteOption) ConsoleRouteAnnotation

ConsoleRoute declares a schema's console route; with no options it opts the schema into route generation with full convention defaults

func (*ConsoleRouteAnnotation) Decode added in v0.31.0

func (a *ConsoleRouteAnnotation) Decode(annotation any) error

Decode unmarshals the ConsoleRouteAnnotation

func (ConsoleRouteAnnotation) Name added in v0.31.0

func (a ConsoleRouteAnnotation) Name() string

Name returns the name of the ConsoleRouteAnnotation

type ConsoleRouteOption added in v0.31.0

type ConsoleRouteOption func(*ConsoleRouteAnnotation)

ConsoleRouteOption configures a ConsoleRouteAnnotation deviation from convention

func WithConsoleBase added in v0.31.0

func WithConsoleBase(base string) ConsoleRouteOption

WithConsoleBase overrides the console landing path for a schema

func WithConsoleIDParam added in v0.31.0

func WithConsoleIDParam(param string) ConsoleRouteOption

WithConsoleIDParam routes object links through a query parameter instead of a path segment

func WithConsoleSuffix added in v0.31.0

func WithConsoleSuffix(suffix string) ConsoleRouteOption

WithConsoleSuffix appends a path segment after the object ID in object links

type DBOption

type DBOption func(opts *EntClientConfig)

DBOption allows users to optionally supply configuration to the ent connection

func WithSecondaryDB

func WithSecondaryDB() DBOption

WithSecondaryDB sets the secondary db connection if the driver supports multiwrite

type DecodableAnnotation added in v0.29.0

type DecodableAnnotation interface {
	schema.Annotation
	Decode(annotation any) error
}

DecodableAnnotation is an annotation that can decode itself from a raw value

type DisplayNameAnnotation added in v0.32.0

type DisplayNameAnnotation struct{}

DisplayNameAnnotation marks the single field carrying a schema's display name; at most one field per schema may carry it

func DisplayName added in v0.32.0

func DisplayName() DisplayNameAnnotation

DisplayName marks a field as the schema's display-name field

func (DisplayNameAnnotation) Name added in v0.32.0

func (a DisplayNameAnnotation) Name() string

Name returns the name of the DisplayNameAnnotation

type EntClientConfig

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

EntClientConfig configures the entsql drivers

func NewDBConfig

func NewDBConfig(c Config, opts ...DBOption) (*EntClientConfig, error)

NewDBConfig returns a new ent database configuration

func (*EntClientConfig) GetPrimaryDB

func (c *EntClientConfig) GetPrimaryDB() *entsql.Driver

GetPrimaryDB returns the primary database configuration

func (*EntClientConfig) GetSecondaryDB

func (c *EntClientConfig) GetSecondaryDB() *entsql.Driver

GetSecondaryDB returns the secondary db connection

func (*EntClientConfig) NewEntDB

func (c *EntClientConfig) NewEntDB(dataSource string) (*entsql.Driver, error)

NewEntDB creates a new ent database connection

type Exportable added in v0.11.0

type Exportable struct {
	// OrgOwned indicates if the schema is owned by an organization and will automatically add the ownerID filter during export validation.
	OrgOwned bool
	// HasSystemOwned indicates if the schema has systemOwned field and will automatically add the systemOwned=false filter during export validation.
	HasSystemOwned bool
}

Exportable annotation marks a schema as exportable. This annotation can be used to indicate that a schema supports export functionality and should be included in export validation.

Usage:

func (MySchema) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entx.Exportable{},
	}
}

func NewExportable added in v0.21.0

func NewExportable(opts ...ExportableOption) Exportable

NewExportable creates a new Exportable annotation with the given options.

func (*Exportable) Decode added in v0.11.0

func (a *Exportable) Decode(annotation any) error

Decode unmarshalls the Exportable annotation

func (Exportable) Name added in v0.11.0

func (Exportable) Name() string

Name returns the name of the Exportable annotation.

type ExportableGenerator added in v0.11.0

type ExportableGenerator struct {
	// SchemaPath is the path to the schema directory
	SchemaPath string
	// OutputDir is the directory where the generated file will be written
	OutputDir string
	// Package is the package name for the generated file
	Package string
	// ImportPath is the import path for the enums package
	ImportPath string
}

ExportableGenerator handles the generation of exportable schema validation.

This generator scans ent schemas for the Exportable annotation and generates validation code that can be used to verify export requests.

Usage:

// In your entc.go file:
generator := entx.NewExportableGenerator("./schema", "./internal/hooks")
err := generator.Generate()
if err != nil {
	log.Fatal(err)
}

The generator will create a file with functions like:

func IsSchemaExportable(schemaName string) bool {
	return ExportableSchemas[strings.ToLower(schemaName)]
}

func ValidateExportType(exportType string) error {
	// Returns error if schema is not exportable
}

Example schema annotation:

func (MySchema) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entx.NewExportable(), // Marks this schema as exportable
	}
}

func NewExportableGenerator added in v0.11.0

func NewExportableGenerator(schemaPath, outputDir string) *ExportableGenerator

NewExportableGenerator creates a new ExportableGenerator with default settings.

func (*ExportableGenerator) Generate added in v0.11.0

func (e *ExportableGenerator) Generate(flags ...string) error

Generate generates the exportable schemas validation code and ExportType enum.

func (*ExportableGenerator) WithImportPath added in v0.11.0

func (e *ExportableGenerator) WithImportPath(importPath string) *ExportableGenerator

WithImportPath sets the import path for the enums package.

func (*ExportableGenerator) WithPackage added in v0.11.0

func (e *ExportableGenerator) WithPackage(pkg string) *ExportableGenerator

WithPackage sets the package name for the generated file.

type ExportableOption added in v0.21.0

type ExportableOption func(*Exportable)

Options for the Exportable annotation.

type Extension

type Extension struct {
	entc.DefaultExtension
	// contains filtered or unexported fields
}

Extension is an implementation of entc.Extension

func NewExtension

func NewExtension(opts ...ExtensionOption) (*Extension, error)

NewExtension returns an entc Extension that allows the entx package to generate the schema changes and templates needed to function

func (*Extension) GQLSchemaHooks

func (e *Extension) GQLSchemaHooks() []entgql.SchemaHook

GQLSchemaHooks of the extension to seamlessly edit the final gql interface

func (*Extension) Templates

func (e *Extension) Templates() []*gen.Template

Templates of the extension

type ExtensionOption

type ExtensionOption func(*Extension) error

ExtensionOption allow for control over the behavior of the generator

func WithJSONScalar

func WithJSONScalar() ExtensionOption

WithJSONScalar adds the JSON scalar definition

type FGACrudAnnotation added in v0.28.1

type FGACrudAnnotation struct {
	// Skip mode used for fga crud generation
	Skip FGASkipMode
}

FGACrudAnnotation marks the crud operations that are allowed for the schema to generate crud tuples If this annotation is not added, it uses the default based on annotations and policies on the schema

func FGACrudSkip added in v0.28.1

func FGACrudSkip(flags ...FGASkipMode) FGACrudAnnotation

FGACrudSkip returns a skip annotation. The Skip() annotation is used to skip generating crud tuples for fga settings

It gives you the flexibility to skip generating the type or the field based on the SkipMode flags.

func (*FGACrudAnnotation) Decode added in v0.28.1

func (a *FGACrudAnnotation) Decode(annotation any) error

Decode unmarshals the FGACrudAnnotation.

func (FGACrudAnnotation) Name added in v0.28.1

func (a FGACrudAnnotation) Name() string

Name returns the name of the FGACrudAnnotation

type FGAParentCrudAnnotation added in v0.28.1

type FGAParentCrudAnnotation struct {
	// ParentSchemas are schemas that will also give access to this schema
	ParentSchemas []string
}

FGAParentCrudAnnotation indicates parent permission inheritance, e.g. organization setting updates can be inherited via permissions to organization

func FGACrudParent added in v0.28.1

func FGACrudParent(schemas ...string) FGAParentCrudAnnotation

FGACrudParent returns the FGAParentCrudAnnotation with the parent schemas set

func (*FGAParentCrudAnnotation) Decode added in v0.28.1

func (a *FGAParentCrudAnnotation) Decode(annotation any) error

Decode unmarshals the FGAParentCrudAnnotation.

func (FGAParentCrudAnnotation) Name added in v0.28.1

Name returns the name of the FGAParentCrudAnnotation

type FGASkipMode added in v0.28.1

type FGASkipMode int

FGASkipMode is the skip for crud annotations

const (
	// SkipType skips generating fga crud types or fields in the model
	FGASkipType FGASkipMode = 1 << iota
	// SkipCreate skips crud create fga settings
	SkipCreate
	// SkipUpdate skips crud update fga settings
	SkipUpdate
	// SkipDelete skips crud delete fga settings
	SkipDelete

	// SkipAll is default mode to skip all.
	SkipAll = FGASkipType |
		SkipCreate |
		SkipUpdate |
		SkipDelete
)

func (FGASkipMode) Has added in v0.28.1

func (m FGASkipMode) Has(flag FGASkipMode) bool

Has determines if the skip mode contains the flag

type FieldSourceManagedAnnotation added in v0.35.0

type FieldSourceManagedAnnotation struct{}

FieldSourceManagedAnnotation marks a field copied from the catalog row and kept in sync by refresh

func (*FieldSourceManagedAnnotation) Decode added in v0.35.0

func (a *FieldSourceManagedAnnotation) Decode(annotation any) error

Decode unmarshalls the FieldSourceManagedAnnotation

func (FieldSourceManagedAnnotation) Name added in v0.35.0

Name returns the name of the FieldSourceManagedAnnotation

type FieldSourceManagedBuilder added in v0.35.0

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

FieldSourceManagedBuilder provides a fluent interface for FieldSourceManagedAnnotation

func FieldSourceManaged added in v0.35.0

func FieldSourceManaged() *FieldSourceManagedBuilder

FieldSourceManaged marks a field whose value is owned by its upstream source and overwritten on refresh or reconcile

func (*FieldSourceManagedBuilder) MarshalJSON added in v0.35.0

func (b *FieldSourceManagedBuilder) MarshalJSON() ([]byte, error)

MarshalJSON serializes the builder as the underlying FieldSourceManagedAnnotation

func (*FieldSourceManagedBuilder) Name added in v0.35.0

Name returns the annotation name, implementing the ent Annotation interface

type FileCategoryAnnotation added in v0.24.1

type FileCategoryAnnotation struct {
	Category string
}

FileCategoryAnnotation marks a schema with a default file category for uploads.

func FileCategory added in v0.24.1

func FileCategory(category string) FileCategoryAnnotation

FileCategory marks a schema with the default category for files attached to it.

func (*FileCategoryAnnotation) Decode added in v0.24.1

func (a *FileCategoryAnnotation) Decode(annotation any) error

Decode unmarshals the FileCategoryAnnotation.

func (FileCategoryAnnotation) Name added in v0.24.1

func (a FileCategoryAnnotation) Name() string

Name returns the name of the FileCategoryAnnotation

type GroupPermissionsEnabled added in v0.28.1

type GroupPermissionsEnabled struct{}

GroupPermissionsEnabled marks the schema as having group permissions enabled

func (GroupPermissionsEnabled) Name added in v0.28.1

Name returns the name of the GroupPermissionsEnabled

type Info added in v0.21.0

type Info struct {
	HasOwnerField       bool
	HasSystemOwnedField bool
}

type IntegrationMappingFieldAnnotation added in v0.22.3

type IntegrationMappingFieldAnnotation struct {
	// Key is the mapping output key (GraphQL input field name).
	Key string
	// LookupKey indicates the field participates in stock ingest lookup matching
	LookupKey bool
	// SystemControlled excludes the field from provider mappings
	SystemControlled bool
	// Volatile excludes the field from triggering an ingest change
	Volatile bool
}

IntegrationMappingFieldAnnotation marks a field as part of an integration mapping target. Key is optional; when empty, generators should derive the GraphQL input field name from the ent field name (lowerCamel, with initialisms preserved).

func (*IntegrationMappingFieldAnnotation) Decode added in v0.22.3

func (a *IntegrationMappingFieldAnnotation) Decode(annotation any) error

Decode unmarshalls the IntegrationMappingFieldAnnotation

func (IntegrationMappingFieldAnnotation) Name added in v0.22.3

Name returns the name of the IntegrationMappingFieldAnnotation

type IntegrationMappingFieldBuilder added in v0.22.3

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

IntegrationMappingFieldBuilder provides a fluent interface for IntegrationMappingFieldAnnotation.

func IntegrationMappingField added in v0.22.3

func IntegrationMappingField() *IntegrationMappingFieldBuilder

IntegrationMappingField returns a builder for an integration mapping field annotation. The mapping key is derived from the ent field name unless explicitly overridden.

func (*IntegrationMappingFieldBuilder) Key added in v0.22.3

Key overrides the mapping output key (GraphQL input field name)

func (*IntegrationMappingFieldBuilder) LookupKey added in v0.24.0

LookupKey marks the field as part of the stock ingest lookup key

func (*IntegrationMappingFieldBuilder) MarshalJSON added in v0.22.3

func (b *IntegrationMappingFieldBuilder) MarshalJSON() ([]byte, error)

MarshalJSON serializes the builder as the underlying IntegrationMappingFieldAnnotation

func (*IntegrationMappingFieldBuilder) Name added in v0.22.3

Name returns the annotation name, implementing the ent Annotation interface

func (*IntegrationMappingFieldBuilder) SystemControlled added in v0.34.0

SystemControlled excludes the field from provider mappings

func (*IntegrationMappingFieldBuilder) Volatile added in v0.34.0

Volatile excludes the field from triggering an ingest change

type IntegrationMappingSchemaAnnotation added in v0.22.3

type IntegrationMappingSchemaAnnotation struct {
	// StockPersist enables the generated stock ingest mapping and preparation semantics.
	StockPersist bool
	// Include restricts mapping to a specific set of ent field names (snake_case).
	Include []string
	// Exclude removes specific ent field names (snake_case) from mapping.
	Exclude []string
	// LookupAlternatives declares the ordered composite ingest lookup keys as snake_case field name sets
	LookupAlternatives [][]string
	// LookupWhereNull limits lookup matches to rows where these snake_case fields are null, mirroring a partial unique index
	LookupWhereNull []string
	// InstanceScoped treats same-key records from different source instances as distinct rows
	InstanceScoped bool
}

IntegrationMappingSchemaAnnotation marks a schema as an integration mapping target. When present, generators should include all eligible fields by default.

func (*IntegrationMappingSchemaAnnotation) Decode added in v0.22.3

func (a *IntegrationMappingSchemaAnnotation) Decode(annotation any) error

Decode unmarshalls the IntegrationMappingSchemaAnnotation

func (IntegrationMappingSchemaAnnotation) Name added in v0.22.3

Name returns the name of the IntegrationMappingSchemaAnnotation

type IntegrationMappingSchemaBuilder added in v0.22.3

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

IntegrationMappingSchemaBuilder provides a fluent interface for IntegrationMappingSchemaAnnotation.

func IntegrationMappingSchema added in v0.22.3

func IntegrationMappingSchema() *IntegrationMappingSchemaBuilder

IntegrationMappingSchema returns a builder for an integration mapping schema annotation.

func (*IntegrationMappingSchemaBuilder) Exclude added in v0.22.3

Exclude removes specific ent field names (snake_case) from mapping

func (*IntegrationMappingSchemaBuilder) Include added in v0.22.3

Include restricts mapping to a specific set of ent field names (snake_case)

func (*IntegrationMappingSchemaBuilder) InstanceScoped added in v0.34.0

InstanceScoped marks records with the same natural key but a different source instance as distinct rows

func (*IntegrationMappingSchemaBuilder) LookupAlternative added in v0.34.0

LookupAlternative appends one ordered composite ingest lookup key of snake_case field names

func (*IntegrationMappingSchemaBuilder) LookupWhereNull added in v0.36.3

LookupWhereNull limits lookup matches to rows where the given snake_case fields are null

func (*IntegrationMappingSchemaBuilder) MarshalJSON added in v0.22.3

func (b *IntegrationMappingSchemaBuilder) MarshalJSON() ([]byte, error)

MarshalJSON serializes the builder as the underlying IntegrationMappingSchemaAnnotation

func (*IntegrationMappingSchemaBuilder) Merge added in v0.34.0

Merge combines a schema-level mapping annotation with the mixed-in one

func (*IntegrationMappingSchemaBuilder) Name added in v0.22.3

Name returns the annotation name, implementing the ent Annotation interface

func (*IntegrationMappingSchemaBuilder) StockPersist added in v0.24.0

StockPersist enables the generated stock ingest mapping and preparation semantics.

type MatchAlternativeFieldAnnotation added in v0.38.7

type MatchAlternativeFieldAnnotation struct {
	// Fields are the snake_case column names matched alongside the annotated field
	Fields []string
}

MatchAlternativeFieldAnnotation lists other columns of the same schema a field's ingest lookup also matches against

func FieldMatchAlternative added in v0.38.7

func FieldMatchAlternative(fields ...string) *MatchAlternativeFieldAnnotation

FieldMatchAlternative returns a new MatchAlternativeFieldAnnotation so ingest lookups on the field also match the given columns

func (*MatchAlternativeFieldAnnotation) Decode added in v0.38.7

func (a *MatchAlternativeFieldAnnotation) Decode(annotation any) error

Decode unmarshalls the MatchAlternativeFieldAnnotation

func (MatchAlternativeFieldAnnotation) Name added in v0.38.7

Name returns the name of the MatchAlternativeFieldAnnotation

type MentionSourceAnnotation added in v0.32.0

type MentionSourceAnnotation struct{}

MentionSourceAnnotation marks a rich-text field scanned for mentions; the generator classifies the field by its ent type: JSON fields carry the slate document and string fields carry the plain-text fallback

func MentionSource added in v0.32.0

func MentionSource() MentionSourceAnnotation

MentionSource marks a rich-text field for mention scanning

func (MentionSourceAnnotation) Name added in v0.32.0

Name returns the name of the MentionSourceAnnotation

type MultiWriteDriver

type MultiWriteDriver struct {
	// Wp (write-primary), Ws (write-secondary) Drivers
	Wp, Ws dialect.Driver
}

MultiWriteDriver allows you to write to a primary and secondary database

func (*MultiWriteDriver) BeginTx

func (d *MultiWriteDriver) BeginTx(ctx context.Context, opts *sql.TxOptions) (dialect.Tx, error)

BeginTx adds an log-id for the transaction and calls the underlying driver BeginTx command if it is supported.

func (*MultiWriteDriver) Close

func (d *MultiWriteDriver) Close() error

Close the underlying connections

func (*MultiWriteDriver) Dialect

func (d *MultiWriteDriver) Dialect() string

Dialect returns the dialect name of the primary driver

func (*MultiWriteDriver) Exec

func (d *MultiWriteDriver) Exec(ctx context.Context, query string, args, v any) error

Exec logs its params and calls the underlying driver Exec method for both write drivers

func (*MultiWriteDriver) Query

func (d *MultiWriteDriver) Query(ctx context.Context, query string, args, v any) error

Query will query the primary write database

func (*MultiWriteDriver) Tx

Tx wraps the Exec and Query operations in transaction.

type OrgOwnedSchema added in v0.29.0

type OrgOwnedSchema struct{}

OrgOwnedSchema marks the schema as being org owned

func (OrgOwnedSchema) Name added in v0.29.0

func (a OrgOwnedSchema) Name() string

Name returns the name of the OrgOwnedSchema

type QueryGenAnnotation

type QueryGenAnnotation struct {
	Skip bool
}

QueryGenAnnotation is an annotation used to indicate that query generation should be skipped for this type

func QueryGenSkip

func QueryGenSkip(skip bool) *QueryGenAnnotation

QueryGenSkip sets whether the query generation should be skipped for this type

func (*QueryGenAnnotation) Decode

func (a *QueryGenAnnotation) Decode(annotation any) error

Decode unmarshalls the QueryGenAnnotation

func (QueryGenAnnotation) Name

func (a QueryGenAnnotation) Name() string

Name returns the name of the QueryGenAnnotation

type SchemaGenAnnotation

type SchemaGenAnnotation struct {
	// Skip indicates that the schema generation should be skipped for this type
	Skip bool
	// SkipSearch indicates that the schema should not be searchable
	// Schemas are also not searchable if no fields are marked as searchable
	SkipSearch bool
}

SchemaGenAnnotation is an annotation used to indicate that schema generation should be skipped for this type When Skip is true, the search schema generation is always skipped SkipSearch allow for schemas to be be opt out of search schema generation

func SchemaGenSkip

func SchemaGenSkip(skip bool) *SchemaGenAnnotation

SchemaGenSkip sets whether the schema generation should be skipped for this type

func SchemaSearchable

func SchemaSearchable(s bool) *SchemaGenAnnotation

SchemaSearchable sets if the schema should be searchable and generated in the search schema template

func (*SchemaGenAnnotation) Decode

func (a *SchemaGenAnnotation) Decode(annotation any) error

Decode unmarshalls the SchemaGenAnnotation

func (SchemaGenAnnotation) Name

func (a SchemaGenAnnotation) Name() string

Name returns the name of the SchemaGenAnnotation

type SearchFieldAnnotation

type SearchFieldAnnotation struct {
	// Searchable indicates that the field should be searchable
	Searchable bool
	// ExcludeAdmin indicates that the field will be excluded from the admin search which includes all fields by default
	ExcludeAdmin bool
	// JSONPath is the path to the field in the JSON object
	JSONPath string
	// JSONDotPath is the path to the field in the JSON object using dot notation
	JSONDotPath string
}

SearchFieldAnnotation is an annotation used to indicate that the field should be searchable

func FieldAdminSearchable added in v0.1.5

func FieldAdminSearchable(s bool) *SearchFieldAnnotation

FieldAdminSearchable returns a new SearchFieldAnnotation with the exclude admin searchable flag set

func FieldJSONDotPathSearchable added in v0.1.7

func FieldJSONDotPathSearchable(path string) *SearchFieldAnnotation

FieldJSONDotPathSearchable returns a new SearchFieldAnnotation with the searchable flag set and the JSONDotPath set

func FieldJSONPathSearchable added in v0.1.7

func FieldJSONPathSearchable(path string) *SearchFieldAnnotation

FieldJSONPathSearchable returns a new SearchFieldAnnotation with the searchable flag set and the JSONPath set

func FieldSearchable

func FieldSearchable() *SearchFieldAnnotation

FieldSearchable returns a new SearchFieldAnnotation with the searchable flag set

func (*SearchFieldAnnotation) Decode

func (a *SearchFieldAnnotation) Decode(annotation any) error

Decode unmarshalls the SearchFieldAnnotation

func (SearchFieldAnnotation) Name

func (a SearchFieldAnnotation) Name() string

Name returns the name of the SearchFieldAnnotation

type SkipQueryCheckForModuleAnnotation added in v0.38.4

type SkipQueryCheckForModuleAnnotation struct{}

SkipQueryCheckForModuleAnnotation allows certain queries to be executed regardless of module checks.

func SkipQueryCheckForModule added in v0.38.4

func SkipQueryCheckForModule() SkipQueryCheckForModuleAnnotation

SkipQueryCheckForModule returns a new SearchFieldAnnotation with the flag set

func (*SkipQueryCheckForModuleAnnotation) Decode added in v0.38.4

func (a *SkipQueryCheckForModuleAnnotation) Decode(annotation any) error

Decode unmarshalls the SkipQueryCheckForModuleAnnotation

func (SkipQueryCheckForModuleAnnotation) Name added in v0.38.4

Name returns the name of the SkipQueryCheckForModuleAnnotation

type SnapshotRemovalAnnotation added in v0.34.0

type SnapshotRemovalAnnotation struct {
	// Episodic treats removal as a recurring observation rather than a permanent tombstone
	Episodic bool
}

SnapshotRemovalAnnotation marks the field recording when a record was removed from its source

func (*SnapshotRemovalAnnotation) Decode added in v0.34.0

func (a *SnapshotRemovalAnnotation) Decode(annotation any) error

Decode unmarshalls the SnapshotRemovalAnnotation

func (SnapshotRemovalAnnotation) Name added in v0.34.0

Name returns the name of the SnapshotRemovalAnnotation

type SnapshotRemovalBuilder added in v0.34.0

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

SnapshotRemovalBuilder provides a fluent interface for SnapshotRemovalAnnotation

func SnapshotRemoval added in v0.34.0

func SnapshotRemoval() *SnapshotRemovalBuilder

SnapshotRemoval marks the field recording when a record was removed from its source

func (*SnapshotRemovalBuilder) Episodic added in v0.34.0

Episodic marks removal as a recurring observation rather than a permanent tombstone

func (*SnapshotRemovalBuilder) MarshalJSON added in v0.34.0

func (b *SnapshotRemovalBuilder) MarshalJSON() ([]byte, error)

MarshalJSON serializes the builder as the underlying SnapshotRemovalAnnotation

func (*SnapshotRemovalBuilder) Name added in v0.34.0

func (b *SnapshotRemovalBuilder) Name() string

Name returns the annotation name, implementing the ent Annotation interface

type SystemOwnedSchema added in v0.29.0

type SystemOwnedSchema struct{}

SystemOwnedSchema marks the schema as being able to have system owned objects

func (SystemOwnedSchema) Name added in v0.29.0

func (a SystemOwnedSchema) Name() string

Name returns the name of the SystemOwnedSchema

type TaskRuleAnnotation added in v0.30.2

type TaskRuleAnnotation struct {
	Rules []TaskRuleSpec
}

TaskRuleAnnotation marks a field (or schema, via SchemaTaskRule) as a source of suggested-task generation. Each rule is evaluated independently when the owning entity is created (or updated, for consumers that opt a schema into update-triggering)

func FieldTaskRule added in v0.30.2

func FieldTaskRule(rules ...TaskRuleSpec) *TaskRuleAnnotation

FieldTaskRule attaches one or more suggested-task rules to a field

func SchemaTaskRule added in v0.30.2

func SchemaTaskRule(rules ...TaskRuleSpec) *TaskRuleAnnotation

SchemaTaskRule attaches one or more unconditional suggested-task rules to the schema itself, fired regardless of field values

func (*TaskRuleAnnotation) Decode added in v0.30.2

func (a *TaskRuleAnnotation) Decode(annotation any) error

Decode unmarshalls the TaskRuleAnnotation

func (TaskRuleAnnotation) Name added in v0.30.2

func (a TaskRuleAnnotation) Name() string

Name returns the name of the TaskRuleAnnotation

type TaskRuleSpec added in v0.30.2

type TaskRuleSpec struct {
	// RuleID identifies which task template to render at rule evaluation time
	RuleID string
	// Expression is a CEL boolean expression; empty always fires
	Expression string
	// EachElement, when set, is a CEL expression resolving to a list within "value"
	EachElement string
	// Trigger selects create-and-update (the default, zero value) or create-only evaluation
	Trigger TaskRuleTrigger
}

TaskRuleSpec declares one suggested-task trigger: a CEL condition plus the RuleID a runtime engine uses to look up the task's template content

type TaskRuleTrigger added in v0.30.2

type TaskRuleTrigger string

TaskRuleTrigger selects which mutation operations a TaskRuleSpec is evaluated on

const (
	// TaskRuleOnCreateOrUpdate evaluates the rule on both create and update. This is the default
	// when Trigger is left unset, since most fields remain editable after creation
	TaskRuleOnCreateOrUpdate TaskRuleTrigger = "createOrUpdate"
	// TaskRuleOnCreateOnly evaluates the rule only when the entity is created; opt into this for
	// fields that can't change afterward (e.g. onboarding's answers)
	TaskRuleOnCreateOnly TaskRuleTrigger = "createOnly"
)

type ThroughCleanup

type ThroughCleanup struct {
	Field   string
	Through string
}

ThroughCleanup is a struct used to indicate the field and through edge to cascade through

type WebhookPayloadFieldAnnotation added in v0.19.0

type WebhookPayloadFieldAnnotation struct {
	// Include indicates that the field should be included in webhook payloads
	Include bool
}

WebhookPayloadFieldAnnotation is an annotation used to indicate that a field should be included in webhook payloads

func FieldWebhookPayloadField added in v0.19.0

func FieldWebhookPayloadField() *WebhookPayloadFieldAnnotation

FieldWebhookPayloadField returns a new WebhookPayloadFieldAnnotation with the include flag set

func (*WebhookPayloadFieldAnnotation) Decode added in v0.19.0

func (a *WebhookPayloadFieldAnnotation) Decode(annotation any) error

Decode unmarshalls the WebhookPayloadFieldAnnotation

func (WebhookPayloadFieldAnnotation) Name added in v0.19.0

Name returns the name of the WebhookPayloadFieldAnnotation

type WorkflowEligibleAnnotation added in v0.18.0

type WorkflowEligibleAnnotation struct {
	// Eligible indicates that the field can be included in workflow definitions and modified via proposed changes
	Eligible bool
}

WorkflowEligibleAnnotation is an annotation used to indicate that a field can be modified via workflow proposed changes

func FieldWorkflowEligible added in v0.18.0

func FieldWorkflowEligible() *WorkflowEligibleAnnotation

FieldWorkflowEligible returns a new WorkflowEligibleAnnotation with the eligible flag set

func (*WorkflowEligibleAnnotation) Decode added in v0.18.0

func (a *WorkflowEligibleAnnotation) Decode(annotation any) error

Decode unmarshalls the WorkflowEligibleAnnotation

func (WorkflowEligibleAnnotation) Name added in v0.18.0

Name returns the name of the WorkflowEligibleAnnotation

Directories

Path Synopsis
Package accessmap provides a entgo extension for generating access maps and helper functions for edge access control
Package accessmap provides a entgo extension for generating access maps and helper functions for edge access control
Package entityops generates shared entity operation helpers — create, update, upsert, query, and field-update — with typed schema descriptors, Gala event infrastructure, and shared operation metadata.
Package entityops generates shared entity operation helpers — create, update, upsert, query, and field-update — with typed schema descriptors, Gala event infrastructure, and shared operation metadata.
Package genhooks provides a set of entgo hooks for generating files from the ent schema.
Package genhooks provides a set of entgo hooks for generating files from the ent schema.
package history provides code generation to add history tables for an ent schema
package history provides code generation to add history tables for an ent schema
Package mixin contains the mixin package
Package mixin contains the mixin package
Package oscalgen provides an entc extension that generates OSCAL mapping metadata
Package oscalgen provides an entc extension that generates OSCAL mapping metadata
vanilla
_example/ent/csvgenerated
Code generated by entx CSV generator.
Code generated by entx CSV generator.
_example/ent/enums
Package enums has enums
Package enums has enums
_example/pkg/celx
Package celx is a minimal CEL evaluation helper standing in for the equivalent core-more package (github.com/theopenlane/core/v2/pkg/celx), providing just the surface entityops-generated code calls: a boolean CEL evaluator bound to a native Go struct type via json tags
Package celx is a minimal CEL evaluation helper standing in for the equivalent core-more package (github.com/theopenlane/core/v2/pkg/celx), providing just the surface entityops-generated code calls: a boolean CEL evaluator bound to a native Go struct type via json tags
_example/pkg/gala
Package gala is a minimal in-memory pub/sub helper standing in for the equivalent core-more package (github.com/theopenlane/core/v2/pkg/gala), providing just the surface entityops-generated code calls: typed topics, listener registration, and synchronous emit dispatch
Package gala is a minimal in-memory pub/sub helper standing in for the equivalent core-more package (github.com/theopenlane/core/v2/pkg/gala), providing just the surface entityops-generated code calls: typed topics, listener registration, and synchronous emit dispatch
_example/tasktemplates
Package tasktemplates is example consumer-side plumbing for task rules, used as examples only
Package tasktemplates is example consumer-side plumbing for task rules, used as examples only

Jump to

Keyboard shortcuts

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