codegen: MakeXyz() fixture factories now take args for required foreign key objects

This commit is contained in:
2026-09-19 21:36:31 -07:00
parent bd5ad7e77b
commit 1592c7d1fc

View File

@@ -101,12 +101,39 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
hasCreatedAt, hasUpdatedAt := tbl.HasAutoTimestamps()
updateTestFields := UpdateTestFields(tbl)
requiredForeignKeys := []pkgschema.Column{}
for _, c := range tbl.Columns {
// Only ordinary object foreign keys use a distinct TargetObjectID Go type;
// code-table foreign keys retain their underlying SQLite type in the generated model.
if c.IsNotNull && c.IsNonCodeTableForeignKey() {
requiredForeignKeys = append(requiredForeignKeys, c)
}
}
requiredForeignKeyParamNames := paramNamesFor(requiredForeignKeys)
// Calls made by this generated test do not create related objects themselves. Pass a
// zero ID so the generated test remains syntactically valid; callers of MakeXyz provide
// IDs of the related objects they create.
makeItemArgs := func() (ret []ast.Expr) {
for range requiredForeignKeys {
ret = append(ret, &ast.BasicLit{Kind: token.INT, Value: "0"})
}
return
}()
// func MakeItem() Item { return Item{} }
makeItemFunc := &ast.FuncDecl{
Name: makeHelperName,
Type: &ast.FuncType{
Params: &ast.FieldList{},
Params: &ast.FieldList{List: func() (ret []*ast.Field) {
for i, c := range requiredForeignKeys {
ret = append(ret, &ast.Field{
Names: []*ast.Ident{ast.NewIdent(requiredForeignKeyParamNames[i])},
Type: GoTypeForColumn(c),
})
}
return
}()},
Results: &ast.FieldList{
List: []*ast.Field{
{Type: ast.NewIdent(tbl.GoTypeName)},
@@ -120,6 +147,13 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
&ast.CompositeLit{
Type: ast.NewIdent(tbl.GoTypeName),
Elts: func() (ret []ast.Expr) {
// `UpdateTestFields()` skips foreign keys, so this will not cause duplicates
for i, c := range requiredForeignKeys {
ret = append(ret, &ast.KeyValueExpr{
Key: ast.NewIdent(c.GoFieldName()),
Value: ast.NewIdent(requiredForeignKeyParamNames[i]),
})
}
for _, c := range updateTestFields {
ret = append(ret, &ast.KeyValueExpr{
Key: ast.NewIdent(c.GoFieldName()),
@@ -242,7 +276,8 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
Tok: map[bool]token.Token{true: token.DEFINE, false: token.ASSIGN}[isFirst],
Rhs: []ast.Expr{
&ast.CallExpr{
Fun: ast.NewIdent("Make" + tbl.GoTypeName),
Fun: ast.NewIdent("Make" + tbl.GoTypeName),
Args: makeItemArgs,
},
},
},
@@ -329,7 +364,7 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
&ast.AssignStmt{
Lhs: []ast.Expr{testObj},
Tok: token.DEFINE,
Rhs: []ast.Expr{&ast.CallExpr{Fun: makeHelperName, Args: nil}},
Rhs: []ast.Expr{&ast.CallExpr{Fun: makeHelperName, Args: makeItemArgs}},
},
// item.Description = <sample value, offset 1>
// ...one assignment per updatable field