Skip to content

Commit 24ed032

Browse files
committed
no-mistakes(review): Kotlin readOnly create fix + C# reset skip
1 parent ab8b258 commit 24ed032

4 files changed

Lines changed: 179 additions & 13 deletions

File tree

‎server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,28 @@ public class ServerOwnedCreateInputTests
8383
]}}
8484
""";
8585

86+
// A legal way to say "the server owns this": the generated increment key and the TPH
87+
// discriminator are themselves @mutability: readOnly. The entity then declares both with
88+
// PRIVATE setters (A_readOnly_field_of_every_shape_has_a_private_setter), so a create that
89+
// reset them (`input.Id = default!;`) would not compile in the adopter's build — CS0122.
90+
private const string ReadOnlyKeyAndDiscriminatorModel = """
91+
{ "metadata.root": { "package": "acme::input", "children": [
92+
{ "object.entity": { "name": "Seal", "@discriminator": "kind", "children": [
93+
{ "source.rdb": { "@table": "seals" } },
94+
{ "field.long": { "name": "id", "@mutability": "readOnly" } },
95+
{ "field.enum": { "name": "kind", "@values": ["A", "B"], "@mutability": "readOnly" } },
96+
{ "field.string": { "name": "label", "@maxLength": 40 } },
97+
{ "identity.primary": { "@fields": "id", "@generation": "increment" } }
98+
]}},
99+
{ "object.entity": { "name": "ASeal", "extends": "Seal", "@discriminatorValue": "A", "children": [
100+
{ "field.int": { "name": "qty" } }
101+
]}},
102+
{ "object.entity": { "name": "BSeal", "extends": "Seal", "@discriminatorValue": "B", "children": [
103+
{ "field.string": { "name": "note", "@maxLength": 40 } }
104+
]}}
105+
]}}
106+
""";
107+
86108
private static string Emit(string model, string generator, string file)
87109
{
88110
var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "input.json")]);
@@ -162,4 +184,53 @@ public void Tph_subtype_create_resets_the_key_and_pins_the_discriminator_to_the_
162184
Assert.Contains("input.Kind = default!;", a);
163185
Assert.True(a.IndexOf("input.Kind = default!;", StringComparison.Ordinal) < a.IndexOf(".Add(input);", StringComparison.Ordinal), a);
164186
}
187+
188+
[Fact]
189+
public void A_readOnly_key_and_readOnly_discriminator_get_no_reset_and_the_model_compiles()
190+
{
191+
// System.Text.Json never binds a private setter, so the resets would be redundant —
192+
// and CS0122. Oracle: the Roslyn compile of the generated tree (the adopter's build);
193+
// the wrong behavior rejected is `input.Id = default!;` / `input.Kind = default!;`
194+
// assigning private-setter properties.
195+
var r = new MetaDataLoader().Load([new InMemoryStringSource(ReadOnlyKeyAndDiscriminatorModel, id: "ro-key.json")]);
196+
Assert.Empty(r.Errors);
197+
var ctx = new GenContext
198+
{
199+
Entities = r.Root.Objects(),
200+
Root = r.Root,
201+
Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal },
202+
};
203+
var sources = new EntityGenerator().Generate(ctx)
204+
.Concat(new DbContextGenerator().Generate(ctx))
205+
.Concat(new FilterAllowlistGenerator().Generate(ctx))
206+
.Concat(new RoutesGenerator().Generate(ctx))
207+
.ToList();
208+
var routes = sources.Single(f => f.Path == "SealRoutes.g.cs").Content;
209+
var post = routes[routes.IndexOf("app.MapPost(", StringComparison.Ordinal)..];
210+
Assert.DoesNotContain("input.Id = default!;", post);
211+
Assert.DoesNotContain("input.Kind = default!;", post);
212+
213+
var trees = sources
214+
.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path))
215+
.ToList();
216+
var paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
217+
var tpa = (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!;
218+
foreach (var p in tpa.Split(Path.PathSeparator)) if (p.Length > 0) paths.Add(p);
219+
paths.Add(typeof(Microsoft.EntityFrameworkCore.DbContext).Assembly.Location);
220+
paths.Add(typeof(Microsoft.EntityFrameworkCore.ModelBuilder).Assembly.Location);
221+
paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location);
222+
paths.Add(typeof(Microsoft.EntityFrameworkCore.PrimaryKeyAttribute).Assembly.Location);
223+
paths.Add(typeof(MetaObjects.Codegen.Runtime.FilterParser).Assembly.Location);
224+
var refs = paths.Where(File.Exists)
225+
.Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList();
226+
var comp = CSharpCompilation.Create(
227+
"ro_key_disc_compile_" + Guid.NewGuid().ToString("N"), trees, refs,
228+
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
229+
var errors = comp.GetDiagnostics()
230+
.Where(d => d.Severity == DiagnosticSeverity.Error)
231+
.Select(d => $"{d.Id}: {d.GetMessage()} @ {d.Location}")
232+
.ToList();
233+
Assert.True(errors.Count == 0,
234+
"readOnly key + readOnly discriminator model must compile:\n" + string.Join("\n", errors));
235+
}
165236
}

‎server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t
596596
bool hasItem = pkType is not null;
597597

598598
var discProp = CSharpNaming.Pascal(tph.DiscriminatorField);
599+
var discField = baseEntity.FindField(tph.DiscriminatorField);
599600
// #484 — the polymorphic base rows carry every subtype's columns, so a credential declared
600601
// on the base OR on any subtype is omitted from them.
601602
var baseCredentials = CredentialNames(baseEntity)
@@ -707,7 +708,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t
707708
// --- Per-subtype CRUD sets ---
708709
var hierarchy = tph.Subtypes.Select(s => s.Entity).Prepend(baseEntity).ToList();
709710
foreach (var st in tph.Subtypes)
710-
AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, ctx.Warn);
711+
AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn);
711712
}
712713

713714
sb.AppendLine();
@@ -1104,17 +1105,22 @@ private static void AppendCreateServerOwned(StringBuilder sb, IReadOnlyList<stri
11041105
// The reset statements AppendCreateServerOwned emits for one entity (empty when it has none, so an
11051106
// entity with an assigned key, no navigation and no discriminator keeps its output byte-identical).
11061107
// A TPH subtype class declares no M:N property of its own — the navigations it carries are its
1107-
// discriminator base class's — so a subtype route passes that base as navOwner.
1108-
private static List<string> ServerOwnedCreateResets(MetaObject entity, MetaRoot root, string? discProp = null, MetaObject? navOwner = null)
1108+
// discriminator base class's — so a subtype route passes that base as navOwner. The key and
1109+
// discriminator resets are SKIPPED when that field is itself @mutability: readOnly: the entity
1110+
// declares it with a private setter (EntityGenerator.SetterFor), so the assignment would be
1111+
// CS0122 — and it is redundant, because System.Text.Json never binds a private setter.
1112+
private static List<string> ServerOwnedCreateResets(MetaObject entity, MetaRoot root, MetaField? discField = null, MetaObject? navOwner = null)
11091113
{
11101114
var list = new List<string>();
11111115
if (entity.PrimaryIdentity() is MetaPrimaryIdentity pk
11121116
&& pk.Generation is MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT
11131117
or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID
11141118
&& pk.Fields is [var keyName]
1115-
&& entity.Fields().FirstOrDefault(f => f.Name == keyName) is { } keyField)
1119+
&& entity.Fields().FirstOrDefault(f => f.Name == keyName) is { } keyField
1120+
&& !keyField.IsReadOnlyMutability)
11161121
list.Add($"input.{CSharpNaming.Pascal(keyField.Name)} = default!;");
1117-
if (discProp is not null) list.Add($"input.{discProp} = default!;");
1122+
if (discField is not null && !discField.IsReadOnlyMutability)
1123+
list.Add($"input.{CSharpNaming.Pascal(discField.Name)} = default!;");
11181124
foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, _ => { }))
11191125
{
11201126
var target = CSharpNaming.Pascal(nav.Target.Name);
@@ -1444,7 +1450,7 @@ private static void AppendPartialMergeLoop(
14441450
// that never touches the PK or the discriminator.
14451451
private static void AppendTphSubtypeRoutes(
14461452
StringBuilder sb, TphSubtypePlan st, IReadOnlyList<MetaObject> hierarchy, MetaRoot root, string baseRoute, string baseCls, string dbSet,
1447-
string pkType, string pkProp, string discProp, Action<string> onWarn)
1453+
string pkType, string pkProp, string discProp, MetaField? discField, Action<string> onWarn)
14481454
{
14491455
// #362 — field.object columns on a TPH subtype stay out of scope (Program D §6), but a
14501456
// field.map @objectRef is NOT: it reaches the settable set, so its value objects reach
@@ -1517,7 +1523,7 @@ private static void AppendTphSubtypeRoutes(
15171523
CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields,
15181524
parseBody: HasDecimalField(st.Entity),
15191525
deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials,
1520-
serverOwned: ServerOwnedCreateResets(st.Entity, root, discProp, hierarchy[0]),
1526+
serverOwned: ServerOwnedCreateResets(st.Entity, root, discField, hierarchy[0]),
15211527
readOnlyRequired: RequiredReadOnlyProps(st.Entity));
15221528

15231529
// Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped

‎server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -655,18 +655,23 @@ public object KotlinGenUtil {
655655

656656
/**
657657
* True when [field] is SERVER-OWNED on create for [obj]: a component of [obj]'s
658-
* `increment`/`uuid` primary key (the store generates it), or an `@autoSet` column (the
659-
* CRUD path stamps it, issue #203). The caller never supplies either, so a create body
660-
* that omits one is correct — the complement of [isAssignedPrimaryKeyField]. Judged
661-
* against the entity being generated, not `field.parent`: a key idiomatically lives on
662-
* an abstract base and is inherited through `extends`.
658+
* `increment`/`uuid` primary key (the store generates it), an `@autoSet` column (the
659+
* CRUD path stamps it, issue #203), or — on an object with a WRITABLE rest surface —
660+
* a `readOnly` or derived column (the create SECURITY skip never binds it). The caller
661+
* never supplies any of these, so a create body that omits one is correct — the
662+
* complement of [isAssignedPrimaryKeyField]. Judged against the entity being
663+
* generated, not `field.parent`: a key idiomatically lives on an abstract base and is
664+
* inherited through `extends`. A read-only projection keeps its non-null read shape:
665+
* it has no create body to relax for.
663666
*
664667
* Mirrors the Java port's `SERVER_OWNED_ON_CREATE` set (SpringControllerGenerator).
665668
*/
666669
fun isServerOwnedOnCreate(field: MetaField<*>, obj: MetaObject): Boolean {
667670
val pk = obj.primaryIdentity
668671
if (pk != null && pk.isAutoGenerated && pk.fields.contains(field.name)) return true
669-
return autoSetPolicy(field) != null
672+
if (autoSetPolicy(field) != null) return true
673+
if (!com.metaobjects.generator.util.RestSurfaceGate.isWritable(obj)) return false
674+
return isReadOnlyMutability(field) || isDerivedField(field)
670675
}
671676

672677
/**
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package com.metaobjects.generator.kotlin
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper
4+
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
5+
import com.metaobjects.metadata.ktx.loadString
6+
import com.tschuchort.compiletesting.KotlinCompilation
7+
import com.tschuchort.compiletesting.SourceFile
8+
import jakarta.validation.Validation
9+
import java.nio.file.Files
10+
import kotlin.io.path.isRegularFile
11+
import kotlin.io.path.readText
12+
import kotlin.test.Test
13+
import kotlin.test.assertEquals
14+
import kotlin.test.assertNull
15+
import kotlin.test.assertTrue
16+
17+
/**
18+
* A `@required @mutability: readOnly` field must not make an entity UNCREATABLE (1.2.x):
19+
* the create SECURITY skip drops the column from the insert, so the request-body data
20+
* class must not demand the value either — nullable, default-null, no `@field:NotNull` —
21+
* the same relaxation the generated key and `@autoSet` already get. The cross-port
22+
* contract is `docs/features/generated-mutations.md` "Create stores only what a client
23+
* may set": a body omitting a server-owned field is CORRECT, never a 400.
24+
*
25+
* Executes the two boundary stages a real Spring create runs, exactly as
26+
* [ValidationConformanceTest] does: Jackson (jackson-module-kotlin, constructor binding)
27+
* deserialization of the body onto the COMPILED generated data class, then the jakarta
28+
* Validator over the bound instance. The insert-side drop (client value never stored) is
29+
* gated by the api-contract `input-server-owned-dropped` scenarios. Oracle: the cross-port
30+
* rule above; the wrong behavior rejected is the pre-fix 400 — a missing non-null creator
31+
* parameter with no default, or a `@NotNull` violation on the omitted value.
32+
*/
33+
@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class)
34+
class KotlinServerOwnedCreateBindTest {
35+
36+
private val model = """{
37+
"metadata.root": { "package": "acme::bind", "children": [
38+
{ "object.entity": { "name": "Doc", "children": [
39+
{ "source.rdb": { "@table": "docs" } },
40+
{ "field.long": { "name": "id" } },
41+
{ "field.string": { "name": "title", "@required": true, "@maxLength": 100 } },
42+
{ "field.string": { "name": "role", "@required": true, "@maxLength": 20, "@mutability": "readOnly" } },
43+
{ "identity.primary": { "@fields": "id", "@generation": "increment" } }
44+
] } }
45+
] }
46+
}""".trimIndent()
47+
48+
@Test
49+
fun `create body binds and validates with the readOnly field omitted and present`() {
50+
val out = Files.createTempDirectory("kowned-bind-")
51+
try {
52+
val loader = loadString("owned-bind", model)
53+
KotlinEntityGenerator().apply { setArgs(mapOf("outputDir" to out.toString())) }.execute(loader)
54+
55+
val sources = Files.walk(out).filter { it.isRegularFile() }.sorted().toList()
56+
.map { path -> SourceFile.kotlin(path.parent.relativize(path).toString().replace('/', '_'), path.readText()) }
57+
val compileResult = KotlinCompilation().apply {
58+
this.sources = sources
59+
inheritClassPath = true
60+
messageOutputStream = System.out
61+
}.compile()
62+
assertEquals(KotlinCompilation.ExitCode.OK, compileResult.exitCode,
63+
"generated Doc.kt failed to compile:\n${compileResult.messages}")
64+
65+
val docClass = compileResult.classLoader.loadClass("acme.bind.Doc")
66+
val mapper = ObjectMapper().registerKotlinModule()
67+
val validator = Validation.buildDefaultValidatorFactory().validator
68+
69+
// Omitted: pre-fix this cannot bind (non-null creator param, no default) → 400.
70+
val omitted = mapper.readValue("""{"title":"t"}""", docClass)
71+
assertTrue(validator.validate(omitted).isEmpty(), "omitted readOnly field must not be demanded")
72+
73+
// Present: binds (client value never reaches the insert — api-contract scenario)
74+
// and validates; pre-fix the column skip then hit the NOT NULL column → 500.
75+
val present = mapper.readValue("""{"title":"t","role":"evil"}""", docClass)
76+
assertTrue(validator.validate(present).isEmpty(), "present readOnly value must not be rejected")
77+
78+
// The omitted binding relaxed the property: nullable, defaulted to null.
79+
assertNull(docClass.getMethod("getRole").invoke(omitted))
80+
} finally {
81+
out.toFile().deleteRecursively()
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)