New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for generated columns #3168
Comments
Atlas supports it, but Ent does not support it yet. It should be added to Ent, and suggestions for API are welcome. |
I think sticking close to Atlas API-wise would be nice. A A temporary way to use generated columnsWith hooks / diff hooks and some cheating I've been able to use PostgreSQL generated columns in one of my ents with no issues so far, although it really is a bit janky. We're also not using any of the GraphQL functionality in Ent (and don't plan to), so it may cause problems with that. In my schema, field: field.Enum("status").
Values("draft", "published", "archived").
Immutable().
Optional() // to skip Ent's validation on create Hook to avoid people manually setting anything in the generated column: hook.On(
// Forbid setting status, since it is generated
func(next ent.Mutator) ent.Mutator {
return hook.MyEntFunc(func(ctx context.Context, m *gen.MyEntMutation) (ent.Value, error) {
_, exists := m.Status()
if exists {
return nil, fmt.Errorf("status is generated, cannot be updated manually")
}
return next.Mutate(ctx, m)
})
},
ent.OpCreate|ent.OpUpdate|ent.OpUpdateOne,
), And then in my migrate/main.go, which generates an Atlas versioned migration: ...
schema.WithDiffHook(statusDiffHook),
...
func statusDiffHook(next schema.Differ) schema.Differ {
return schema.DiffFunc(func(current, desired *atlasSchema.Schema) ([]atlasSchema.Change, error) {
for _, table := range desired.Tables {
if table.Name == "my_ent" {
for _, column := range table.Columns {
if column.Name == "status" {
column.SetNull(false)
column.SetGeneratedExpr(&atlasSchema.GeneratedExpr{
Expr: `CASE WHEN "archived_at" IS NOT NULL THEN 'archived' WHEN "published_at" IS NOT NULL THEN 'published' ELSE 'draft' END`,
})
}
}
}
}
changes, err := next.Diff(current, desired)
if err != nil {
return nil, err
}
return changes, nil
})
} I'm not sure how safe/smart it is to mutate the Atlas schema in a diff hook, but it works. |
@Ambroos thanks a bunch for that snippet! @a8m I think that having |
I'm getting the following error the second time I ran the diff:
|
I'm wonder if
entgo
supports generated columns as stated here. If so, is there any place on the documentation to configure a column to be generated always?Thanks in advance for the help!!
The text was updated successfully, but these errors were encountered: