dialect/entsql: allow to define auto increment start value (#4292)

Preparation to rewrite the universal id feature to rely on type ranges defined statically in the schema instead of dynamically in a database.
This commit is contained in:
Jannik Clausen
2025-01-09 20:03:39 +01:00
committed by GitHub
parent d5c8b282de
commit adfd86c303
4 changed files with 33 additions and 3 deletions

View File

@@ -896,12 +896,19 @@ func (a *Atlas) tables(tables []*Table) ([]*schema.Table, error) {
at.SetComment(et.Comment)
}
a.sqlDialect.atTable(et, at)
if a.universalID && et.Name != TypeTable && len(et.PrimaryKey) == 1 {
// universalID is the old implementation of the global unique id, relying on a table in the database.
// The new implementation is based on annotations attached to the schema. Only one can be enabled.
switch {
case a.universalID && et.Annotation != nil && et.Annotation.IncrementStart != nil:
return nil, errors.New("sql/schema: universal id and increment start annotation are mutually exclusive")
case a.universalID && et.Name != TypeTable && len(et.PrimaryKey) == 1:
r, err := a.pkRange(et)
if err != nil {
return nil, err
}
a.sqlDialect.atIncrementT(at, r)
case et.Annotation != nil && et.Annotation.IncrementStart != nil:
a.sqlDialect.atIncrementT(at, *et.Annotation.IncrementStart)
}
if err := a.aColumns(et, at); err != nil {
return nil, err

View File

@@ -16,8 +16,10 @@ import (
"ariga.io/atlas/sql/migrate"
"ariga.io/atlas/sql/schema"
"ariga.io/atlas/sql/sqlite"
"ariga.io/atlas/sql/sqltool"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/schema/field"
@@ -416,18 +418,25 @@ func TestAtlas_StateReader(t *testing.T) {
realm, err := m.StateReader(&Table{
Name: "users",
Columns: []*Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "name", Type: field.TypeString},
{Name: "active", Type: field.TypeBool},
},
Annotation: &entsql.Annotation{
IncrementStart: func(i int64) *int64 { return &i }(100),
},
}).ReadState(context.Background())
require.NoError(t, err)
require.NotNil(t, realm)
require.Len(t, realm.Schemas, 1)
require.Len(t, realm.Schemas[0].Tables, 1)
require.Equal(t, realm.Schemas[0].Tables[0].Name, "users")
require.Equal(t, "users", realm.Schemas[0].Tables[0].Name)
require.Equal(t, []schema.Attr{&sqlite.AutoIncrement{Seq: 100}}, realm.Schemas[0].Tables[0].Attrs)
require.Equal(t,
realm.Schemas[0].Tables[0].Columns,
[]*schema.Column{
schema.NewIntColumn("id", "integer").
AddAttrs(&sqlite.AutoIncrement{}),
schema.NewStringColumn("name", "text"),
schema.NewBoolColumn("active", "bool"),
},