From 7ba311f3f5cb3f04edefc3073e5ea510caf2d284 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 20:45:07 -0500 Subject: [PATCH 1/8] fix(codegen-base): make writer helpers protected and refuse unparsable files in the layout ratchet CodeWriter.describe and JavaWriter.simpleName follow the spec rule that writer methods are public or protected, never private. The layout analyzer now throws when javac reports a syntax error, so a generator file that does not parse is never counted as clean. --- .../metaobjects/generator/writer/CodeWriter.java | 2 +- .../metaobjects/generator/writer/JavaWriter.java | 2 +- .../generator/writer/layout/LayoutAnalyzer.java | 16 +++++++++++++++- .../writer/layout/LayoutRatchetTest.java | 10 ++++++++++ 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java index fe77e5be81..f26880b748 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java @@ -271,7 +271,7 @@ protected static int widthOf(String s) { return s.codePointCount(0, s.length()); } - private static String describe(Object p) { + protected static String describe(Object p) { if (p == null) return "null"; return "an object (" + p.getClass().getName() + ")"; } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java index 5d6707035e..80f31af3be 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java @@ -177,7 +177,7 @@ protected boolean needsImport(String qualifiedName) { return !pkg.equals(JAVA_LANG) && !pkg.equals(packageName); } - private static String simpleName(String qualified) { + protected static String simpleName(String qualified) { return qualified.substring(qualified.lastIndexOf('.') + 1); } } diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java index 0f339ca7a1..23ab5ba7e9 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java @@ -27,6 +27,8 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; @@ -123,13 +125,25 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) { return source; } }; - JavacTask task = (JavacTask) compiler.getTask(null, null, null, List.of("-proc:none"), null, List.of(file)); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + JavacTask task = + (JavacTask) compiler.getTask(null, null, diagnostics, List.of("-proc:none"), null, List.of(file)); Iterable units; try { units = task.parse(); } catch (IOException e) { throw new IllegalStateException("cannot parse " + fileName, e); } + // A file that does not parse is never "clean": the scan would walk a partial tree and miss offenders. + List broken = new ArrayList<>(); + for (Diagnostic d : diagnostics.getDiagnostics()) { + if (d.getKind() == Diagnostic.Kind.ERROR) { + broken.add("line " + d.getLineNumber() + ": " + d.getMessage(null)); + } + } + if (!broken.isEmpty()) { + throw new IllegalStateException("cannot parse " + fileName + ": " + String.join("; ", broken)); + } SourcePositions positions = Trees.instance(task).getSourcePositions(); List findings = new ArrayList<>(); for (CompilationUnitTree unit : units) { diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java index 86d062bac5..6813bf2d16 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java @@ -44,6 +44,16 @@ private static List sorted(Kind... k) { // ── 1. the analyzer ────────────────────────────────────────────────────────────────── + @Test + public void a_file_that_does_not_parse_is_refused_not_treated_as_clean() { + try { + LayoutAnalyzer.analyze("Broken.java", "class Broken { void f() { String s = \"a\\nb\"; "); + org.junit.Assert.fail("a file with a syntax error must not scan as clean"); + } catch (IllegalStateException e) { + org.junit.Assert.assertTrue(e.getMessage(), e.getMessage().startsWith("cannot parse Broken.java")); + } + } + @Test public void catches_a_newline_escape() { assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"a\\nb\";")); From 9ab2046b0c8bfd99193945767f7cee594731ca75 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 20:57:28 -0500 Subject: [PATCH 2/8] feat(metadata): accept every view function and cast in the Java loader Ports the rc.21 view vocabulary to the JVM loader (and so Kotlin): the typed function set beside coalesce, cast with dbColumnType spellings, int-stored enum casts, origin.function validation, union and grain checks, and path operands in correlated filters. The five conformance fixtures the Java ledger excused now pass and the ledger is empty. --- .../conformance-expected-failures.json | 9 +- .../metaobjects/attr/ExpressionAttribute.java | 278 ++++++++++-- .../io/json/CanonicalJsonSerializer.java | 3 +- .../metaobjects/loader/ValidationPhase.java | 400 ++++++++++++++++-- .../metaobjects/origin/FunctionOrigin.java | 6 +- .../ViewExpressionsTypesMetaDataProvider.java | 6 + .../attr/ExpressionViewVocabularyTest.java | 200 +++++++++ 7 files changed, 831 insertions(+), 71 deletions(-) create mode 100644 server/java/metadata/src/test/java/com/metaobjects/attr/ExpressionViewVocabularyTest.java diff --git a/server/java/metadata/conformance-expected-failures.json b/server/java/metadata/conformance-expected-failures.json index 10f1aeecf9..6a7cb91a2c 100644 --- a/server/java/metadata/conformance-expected-failures.json +++ b/server/java/metadata/conformance-expected-failures.json @@ -3,12 +3,5 @@ "_comment": "FR-013/FR-014/FR-015 validation passes shipped. The former subtype-field-override gap (MergedSource envelopes on extends-overrides) is RETIRED: FR-024's addressing-model fix (bare nested names + own-children-only overlay lookup in BaseMetaDataParser) made subtype same-name children SHADOWING REDECLARATIONS per the cross-port contract, which was the root cause \u2014 error-field-readonly-downgrade and field-readonly-upgrade-on-subtype now pass byte-identically.", "_comment_ai_pilot": "ai-trace-* fixtures now pass in Java (@responseRef + template.* child admitted)", "_comment_fr024": "FR-024 validation parity SHIPPED in this port (ValidationPhase.java): subtype rules (identity-name, value purity, projection licensing), projection identity pass-through + key correspondence, source-role B4b cutover (ERR_ENTITY_PRIMARY_SOURCE_READONLY), origin @via single-hop inference + cardinality + extends/origin agreement, and derived-field providability. All 13 FR-024 error fixtures emit their expected code + envelope. Kotlin rides this same JVM loader. B4b landed with the FR-024 projection-codegen increment (proc/view-primary entity fixtures migrated to object.projection).", - "_comment_rc21": "rc.21 view vocabulary validation is not implemented in Java; these fixtures also fail on origin/fix/rc19; implementedIn typescript, csharp. A listed fixture that starts passing fails the run (fixed-but-listed), so remove it from this list then.", - "fixtures": [ - "projection-view-vocabulary-rc21", - "error-computed-cast-enum-not-int-stored", - "error-origin-function-free-sql", - "error-projection-grain-not-object-array", - "error-projection-union-shape" - ] + "fixtures": [] } diff --git a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java index 60c858ff28..15e8eb589d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java +++ b/server/java/metadata/src/main/java/com/metaobjects/attr/ExpressionAttribute.java @@ -11,11 +11,16 @@ import com.metaobjects.field.DateField; import com.metaobjects.field.DecimalField; import com.metaobjects.field.DoubleField; +import com.metaobjects.field.EnumField; import com.metaobjects.field.FloatField; import com.metaobjects.field.IntegerField; import com.metaobjects.field.LongField; +import com.metaobjects.field.MapField; +import com.metaobjects.field.ObjectField; import com.metaobjects.field.StringField; import com.metaobjects.field.TimestampField; +import com.metaobjects.field.UuidField; +import com.metaobjects.database.CoreDBMetaDataProvider; import com.metaobjects.reporting.ReportingConstants; import com.metaobjects.query.FilterOps; import com.metaobjects.registry.MetaDataRegistry; @@ -27,6 +32,7 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; +import java.util.function.Predicate; /** * An Expression Attribute that holds an object-valued {@code attr.expression} value @@ -48,8 +54,9 @@ public class ExpressionAttribute extends MetaAttribute> { public static final String SUBTYPE_EXPRESSION = "expression"; - /** Singleton Gson for round-trip JSON — shared, thread-safe. */ - private static final Gson GSON = new Gson(); + /** Singleton Gson for round-trip JSON — shared, thread-safe. Nulls are kept: a null literal + * ({@code { value: null }}, e.g. under a cast) is part of the tree. */ + private static final Gson GSON = new com.google.gson.GsonBuilder().serializeNulls().create(); // ----------------------------------------------------------------------- // Registration @@ -241,6 +248,78 @@ private static Object jsonElementToJava(JsonElement el) { public static final String EXPR_CASE_OPERAND = "operand"; public static final String EXPR_NOW = ReportingConstants.FILTER_RELATIVE_NOW; public static final String EXPR_NOW_START_OF = ReportingConstants.FILTER_RELATIVE_START_OF; + /** rc.21 part B (U12): {@code { cast: , as: "", dbColumnType?: "" }}. */ + public static final String EXPR_CAST = "cast"; + public static final String EXPR_CAST_AS = "as"; + public static final String EXPR_CAST_DB_COLUMN_TYPE = "dbColumnType"; + /** rc.21 part B (U11, U13): the closed, typed function set beside coalesce. */ + public static final String EXPR_FN_GREATEST = "greatest"; + public static final String EXPR_FN_LEAST = "least"; + public static final String EXPR_FN_NULLIF = "nullif"; + public static final String EXPR_FN_LOWER = "lower"; + public static final String EXPR_FN_UPPER = "upper"; + public static final String EXPR_FN_BTRIM = "btrim"; + public static final String EXPR_FN_SPLIT_PART = "splitPart"; + public static final String EXPR_FN_CONCAT = "concat"; + public static final String EXPR_FN_CONCAT_WS = "concatWs"; + public static final String EXPR_FN_SUBSTRING = "substring"; + public static final String EXPR_FN_REPLACE = "replace"; + public static final String EXPR_FN_LEFT = "left"; + public static final String EXPR_FN_RIGHT = "right"; + public static final String EXPR_FN_LENGTH = "length"; + + /** A function parameter's kind: a string, an integer, any scalar, or the type the "same" ones share. */ + private static final String PARAM_STRING = "string"; + private static final String PARAM_INT = "int"; + private static final String PARAM_SCALAR = "scalar"; + private static final String PARAM_SAME = "same"; + + /** One function's signature: arity, each parameter's kind (the last repeats), and its result. */ + public static final class FnSignature { + public final int min; + public final int max; // Integer.MAX_VALUE for variadic + public final List params; + public final String result; // string | int | same + /** The "same" type must be orderable (greatest / least). */ + public final boolean ordered; + + FnSignature(int min, int max, List params, String result, boolean ordered) { + this.min = min; this.max = max; this.params = params; this.result = result; this.ordered = ordered; + } + } + + private static final int VARIADIC = Integer.MAX_VALUE; + + /** rc.21 part B: every expression function, by name. A closed set, never free SQL. */ + public static final Map EXPR_FUNCTIONS = exprFunctions(); + + private static Map exprFunctions() { + Map m = new LinkedHashMap<>(); + m.put(EXPR_FN_COALESCE, new FnSignature(1, VARIADIC, List.of(PARAM_SAME), PARAM_SAME, false)); + m.put(EXPR_FN_GREATEST, new FnSignature(1, VARIADIC, List.of(PARAM_SAME), PARAM_SAME, true)); + m.put(EXPR_FN_LEAST, new FnSignature(1, VARIADIC, List.of(PARAM_SAME), PARAM_SAME, true)); + m.put(EXPR_FN_NULLIF, new FnSignature(2, 2, List.of(PARAM_SAME, PARAM_SAME), PARAM_SAME, false)); + m.put(EXPR_FN_LOWER, new FnSignature(1, 1, List.of(PARAM_STRING), PARAM_STRING, false)); + m.put(EXPR_FN_UPPER, new FnSignature(1, 1, List.of(PARAM_STRING), PARAM_STRING, false)); + m.put(EXPR_FN_BTRIM, new FnSignature(1, 2, List.of(PARAM_STRING, PARAM_STRING), PARAM_STRING, false)); + m.put(EXPR_FN_SPLIT_PART, new FnSignature(3, 3, List.of(PARAM_STRING, PARAM_STRING, PARAM_INT), PARAM_STRING, false)); + m.put(EXPR_FN_CONCAT, new FnSignature(1, VARIADIC, List.of(PARAM_SCALAR), PARAM_STRING, false)); + m.put(EXPR_FN_CONCAT_WS, new FnSignature(2, VARIADIC, List.of(PARAM_STRING, PARAM_SCALAR), PARAM_STRING, false)); + m.put(EXPR_FN_SUBSTRING, new FnSignature(2, 3, List.of(PARAM_STRING, PARAM_INT, PARAM_INT), PARAM_STRING, false)); + m.put(EXPR_FN_REPLACE, new FnSignature(3, 3, List.of(PARAM_STRING, PARAM_STRING, PARAM_STRING), PARAM_STRING, false)); + m.put(EXPR_FN_LEFT, new FnSignature(2, 2, List.of(PARAM_STRING, PARAM_INT), PARAM_STRING, false)); + m.put(EXPR_FN_RIGHT, new FnSignature(2, 2, List.of(PARAM_STRING, PARAM_INT), PARAM_STRING, false)); + m.put(EXPR_FN_LENGTH, new FnSignature(1, 1, List.of(PARAM_STRING), PARAM_INT, false)); + return java.util.Collections.unmodifiableMap(m); + } + + /** The field subtypes a cast may name in {@code as}. */ + public static final List EXPR_CAST_TARGETS = List.of( + StringField.SUBTYPE_STRING, IntegerField.SUBTYPE_INT, LongField.SUBTYPE_LONG, DoubleField.SUBTYPE_DOUBLE, + FloatField.SUBTYPE_FLOAT, DecimalField.SUBTYPE_DECIMAL, BooleanField.SUBTYPE_BOOLEAN, DateField.SUBTYPE_DATE, + TimestampField.SUBTYPE_TIMESTAMP, UuidField.SUBTYPE_UUID); + private static final Set INTEGER_SUBTYPES = orderedSet(IntegerField.SUBTYPE_INT, LongField.SUBTYPE_LONG); + private static final Set NON_SCALAR_SUBTYPES = orderedSet(ObjectField.SUBTYPE_OBJECT, MapField.SUBTYPE_MAP); /** Boolean composition keys — mirror {@code FilterAttribute}'s private compose keys. */ static final String COMPOSE_AND = "and"; @@ -276,6 +355,71 @@ private static Map> nodeKeys() { return java.util.Collections.unmodifiableMap(m); } + /** + * Why a value of {@code from} cannot be cast to {@code to}, or {@code null} when it can. + * {@code intStoredEnum} is whether the operand is an enum field stored as an integer + * ({@code @intValueMap}). The same table in every port: a cast never makes a value of a kind + * the source cannot hold. Mirrors the TS {@code castProblem}. + */ + public static String castProblem(String from, String to, boolean intStoredEnum) { + if (from == null) return null; // a null literal casts to anything + if (NON_SCALAR_SUBTYPES.contains(from)) return "a field." + from + " value cannot be cast"; + if (from.equals(to)) return null; + if (EnumField.SUBTYPE_ENUM.equals(from)) { + if (StringField.SUBTYPE_STRING.equals(to)) { + return intStoredEnum + ? "an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int" + : null; + } + if (INTEGER_SUBTYPES.contains(to)) { + return intStoredEnum ? null : "only an enum stored as an integer (@intValueMap) can be cast to a number"; + } + return "an enum cannot be cast to " + to; + } + if (StringField.SUBTYPE_STRING.equals(to)) return null; + if (StringField.SUBTYPE_STRING.equals(from)) return null; // the database parses it + // Postgres casts a boolean only to and from integer (int4), so those are the only number casts. + if (NUMERIC_SUBTYPES.contains(to)) { + if (BooleanField.SUBTYPE_BOOLEAN.equals(from)) { + return IntegerField.SUBTYPE_INT.equals(to) ? null : "a boolean casts only to int, not " + to; + } + return NUMERIC_SUBTYPES.contains(from) ? null : "a " + from + " cannot be cast to " + to; + } + if (BooleanField.SUBTYPE_BOOLEAN.equals(to)) { + return IntegerField.SUBTYPE_INT.equals(from) ? null : "a " + from + " cannot be cast to boolean; only an int can"; + } + if (DateField.SUBTYPE_DATE.equals(to) || TimestampField.SUBTYPE_TIMESTAMP.equals(to)) { + return DateField.SUBTYPE_DATE.equals(from) || TimestampField.SUBTYPE_TIMESTAMP.equals(from) + ? null : "a " + from + " cannot be cast to " + to; + } + return "a " + from + " cannot be cast to " + to; + } + + /** + * The first node an expression tree holds that only a view can render (a cast, case, now, a + * function other than coalesce, a path), or {@code null}: a CHECK condition takes none of them. + * Mirrors the TS {@code exprViewOnlyNode}. + */ + public static String exprViewOnlyNode(Object node) { + if (!(node instanceof Map n)) return null; + if (n.containsKey(EXPR_CAST)) return EXPR_CAST; + if (n.containsKey(EXPR_CASE)) return EXPR_CASE; + if (n.containsKey(EXPR_NOW)) return EXPR_NOW; + if (n.containsKey("fn") && !EXPR_FN_COALESCE.equals(n.get("fn"))) return String.valueOf(n.get("fn")); + if (n.get("field") instanceof String f && f.contains(".")) return "the path \"" + f + "\""; + for (String key : List.of("left", "right", "arg")) { + String hit = exprViewOnlyNode(n.get(key)); + if (hit != null) return hit; + } + if (n.get("args") instanceof List args) { + for (Object a : args) { + String hit = exprViewOnlyNode(a); + if (hit != null) return hit; + } + } + return null; + } + /** * Structural well-formedness of an expression tree (known node kinds, ops, * arity). Returns an empty list when valid; each entry is a human-readable @@ -348,18 +492,57 @@ public static List validateExprNode(Object node) { if (n.containsKey(EXPR_CASE_OPERAND)) out.addAll(validateExprNode(n.get(EXPR_CASE_OPERAND))); return out; } + if (n.containsKey(EXPR_CAST)) { + List extra = new ArrayList<>(); + for (String k : n.keySet()) { + if (!k.equals(EXPR_CAST) && !k.equals(EXPR_CAST_AS) && !k.equals(EXPR_CAST_DB_COLUMN_TYPE)) extra.add(k); + } + if (!extra.isEmpty()) { + out.add("expression '" + EXPR_CAST + "' takes only '" + EXPR_CAST_AS + "' and '" + + EXPR_CAST_DB_COLUMN_TYPE + "' beside it, not " + String.join(", ", extra)); + return out; + } + Object to = n.get(EXPR_CAST_AS); + if (!(to instanceof String) || !EXPR_CAST_TARGETS.contains(to)) { + out.add("'" + EXPR_CAST + "' requires '" + EXPR_CAST_AS + "': one of " + String.join(", ", EXPR_CAST_TARGETS)); + return out; + } + if (n.containsKey(EXPR_CAST_DB_COLUMN_TYPE)) { + Object spelling = n.get(EXPR_CAST_DB_COLUMN_TYPE); + boolean legal = spelling instanceof String sp + && CoreDBMetaDataProvider.dbColumnTypeLength(sp) >= 0 + && !CoreDBMetaDataProvider.DB_COLUMN_TYPE_UUID.equals(sp) + && !CoreDBMetaDataProvider.DB_COLUMN_TYPE_JSONB.equals(sp) + && StringField.SUBTYPE_STRING.equals(to); + if (!legal) { + out.add("'" + EXPR_CAST + "' '" + EXPR_CAST_DB_COLUMN_TYPE + "' is a text spelling of @dbColumnType" + + " (text, varchar, character varying, varchar(n), character varying(n), character(n)) with '" + + EXPR_CAST_AS + ": " + StringField.SUBTYPE_STRING + "'"); + return out; + } + } + out.addAll(validateExprNode(n.get(EXPR_CAST))); + return out; + } if (n.containsKey("fn")) { Object fn = n.get("fn"); - if (!EXPR_FN_COALESCE.equals(fn)) { + FnSignature sig = fn instanceof String fnName ? EXPR_FUNCTIONS.get(fnName) : null; + if (sig == null) { out.add("unknown expression fn '" + String.valueOf(fn) + "'"); return out; } + String name = (String) fn; Object args = n.get("args"); - if (args instanceof List && !((List) args).isEmpty()) { - for (Object a : (List) args) out.addAll(validateExprNode(a)); - } else { - out.add("'" + EXPR_FN_COALESCE + "' requires a non-empty args array"); + if (!(args instanceof List) || ((List) args).size() < Math.max(sig.min, 1)) { + out.add(sig.min <= 1 ? "'" + name + "' requires a non-empty args array" + : "'" + name + "' requires at least " + sig.min + " args"); + return out; } + if (((List) args).size() > sig.max) { + out.add("'" + name + "' takes at most " + sig.max + " args, got " + ((List) args).size()); + return out; + } + for (Object a : (List) args) out.addAll(validateExprNode(a)); return out; } if (n.containsKey("op")) { @@ -395,7 +578,7 @@ public static List validateExprNode(Object node) { out.add("unknown expression op '" + op + "'"); return out; } - out.add("expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"); + out.add("expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}"); return out; } @@ -430,6 +613,16 @@ public static final class InferResult { * on a boolean operand is rejected. Mirrors the TS {@code inferExprType}. */ public static InferResult inferExprType(Object node, Function resolveField) { + return inferExprType(node, resolveField, name -> false); + } + + /** + * As {@link #inferExprType(Object, Function)}, with {@code isIntStoredEnum}: whether a + * {@code {field}} names an enum stored as an integer ({@code @intValueMap}), which a cast + * reads. Mirrors the TS {@code inferExprType}. + */ + public static InferResult inferExprType(Object node, Function resolveField, + Predicate isIntStoredEnum) { List structural = validateExprNode(node); if (!structural.isEmpty()) return new InferResult(null, structural); @SuppressWarnings("unchecked") @@ -452,13 +645,13 @@ public static InferResult inferExprType(Object node, Function re if (n.containsKey(EXPR_CASE)) { List errors = new ArrayList<>(); InferResult operand = n.containsKey(EXPR_CASE_OPERAND) - ? inferExprType(n.get(EXPR_CASE_OPERAND), resolveField) : null; + ? inferExprType(n.get(EXPR_CASE_OPERAND), resolveField, isIntStoredEnum) : null; if (operand != null) errors.addAll(operand.errors); List results = new ArrayList<>(); List resultNodes = new ArrayList<>(); for (Object armObj : (List) n.get(EXPR_CASE)) { Map arm = (Map) armObj; - InferResult w = inferExprType(arm.get(EXPR_CASE_WHEN), resolveField); + InferResult w = inferExprType(arm.get(EXPR_CASE_WHEN), resolveField, isIntStoredEnum); errors.addAll(w.errors); if (operand == null && w.type != null && !BooleanField.SUBTYPE_BOOLEAN.equals(w.type)) { errors.add("a searched '" + EXPR_CASE + "' needs a boolean '" + EXPR_CASE_WHEN + "', got " + w.type); @@ -468,13 +661,13 @@ public static InferResult inferExprType(Object node, Function re errors.add("a simple '" + EXPR_CASE + "' compares its " + operand.type + " '" + EXPR_CASE_OPERAND + "' with a " + w.type + " '" + EXPR_CASE_WHEN + "'"); } - InferResult t = inferExprType(arm.get(EXPR_CASE_THEN), resolveField); + InferResult t = inferExprType(arm.get(EXPR_CASE_THEN), resolveField, isIntStoredEnum); errors.addAll(t.errors); results.add(t.type); resultNodes.add(arm.get(EXPR_CASE_THEN)); } if (n.containsKey(EXPR_CASE_ELSE)) { - InferResult e = inferExprType(n.get(EXPR_CASE_ELSE), resolveField); + InferResult e = inferExprType(n.get(EXPR_CASE_ELSE), resolveField, isIntStoredEnum); errors.addAll(e.errors); results.add(e.type); resultNodes.add(n.get(EXPR_CASE_ELSE)); @@ -486,27 +679,60 @@ public static InferResult inferExprType(Object node, Function re } return new InferResult(unified, errors); } - if (n.containsKey("fn")) { // coalesce + if (n.containsKey(EXPR_CAST)) { + Object inner = n.get(EXPR_CAST); + InferResult operand = inferExprType(inner, resolveField, isIntStoredEnum); + String to = (String) n.get(EXPR_CAST_AS); + String fieldRef = inner instanceof Map im && im.get("field") instanceof String f ? f : null; + String problem = castProblem(operand.type, to, fieldRef != null && isIntStoredEnum.test(fieldRef)); + List errors = new ArrayList<>(operand.errors); + if (problem != null) errors.add("'" + EXPR_CAST + "': " + problem); + return new InferResult(to, errors); + } + if (n.containsKey("fn")) { + String name = (String) n.get("fn"); + FnSignature sig = EXPR_FUNCTIONS.get(name); + List args = (List) n.get("args"); List errors = new ArrayList<>(); - List argTypes = new ArrayList<>(); - List args = new ArrayList<>((List) n.get("args")); - for (Object a : args) { - InferResult r = inferExprType(a, resolveField); - errors.addAll(r.errors); - argTypes.add(r.type); + List same = new ArrayList<>(); + List sameNodes = new ArrayList<>(); + for (int i = 0; i < args.size(); i++) { + InferResult a = inferExprType(args.get(i), resolveField, isIntStoredEnum); + errors.addAll(a.errors); + String kind = sig.params.get(Math.min(i, sig.params.size() - 1)); + if (a.type == null) continue; // a null literal fits any parameter + if (PARAM_SAME.equals(kind)) { + same.add(a.type); + sameNodes.add(args.get(i)); + } else if (PARAM_STRING.equals(kind) && !StringField.SUBTYPE_STRING.equals(a.type)) { + errors.add("'" + name + "' argument " + (i + 1) + " must be a string, got " + a.type); + } else if (PARAM_INT.equals(kind) && !IntegerField.SUBTYPE_INT.equals(a.type)) { + // Postgres resolves these functions over int4 only (no implicit bigint to int for a call). + errors.add("'" + name + "' argument " + (i + 1) + " must be an int, got " + a.type + + (LongField.SUBTYPE_LONG.equals(a.type) ? "; cast it ({ cast: , as: int })" : "")); + } else if (PARAM_SCALAR.equals(kind) && NON_SCALAR_SUBTYPES.contains(a.type)) { + errors.add("'" + name + "' argument " + (i + 1) + " must be a scalar, got " + a.type); + } } + // Adaptable literals (an int literal beside a decimal) fit the typed anchor. List differing = new ArrayList<>(); - String unified = unifyTypes(args, argTypes, differing); + String unified = unifyTypes(sameNodes, same, differing); if (!differing.isEmpty()) { - errors.add("'" + EXPR_FN_COALESCE + "' arguments have differing types (" + String.join(", ", differing) + ")"); + errors.add("'" + name + "' arguments have differing types (" + String.join(", ", differing) + ")"); } - return new InferResult(unified, errors); + if (sig.ordered && unified != null + && (BooleanField.SUBTYPE_BOOLEAN.equals(unified) || NON_SCALAR_SUBTYPES.contains(unified))) { + errors.add("'" + name + "' needs ordered arguments, got " + unified); + } + String type = PARAM_SAME.equals(sig.result) ? unified + : PARAM_INT.equals(sig.result) ? IntegerField.SUBTYPE_INT : StringField.SUBTYPE_STRING; + return new InferResult(type, errors); } String op = (String) n.get("op"); if (COMPARISON_OPS.contains(op)) { - InferResult l = inferExprType(n.get("left"), resolveField); - InferResult r = inferExprType(n.get("right"), resolveField); + InferResult l = inferExprType(n.get("left"), resolveField, isIntStoredEnum); + InferResult r = inferExprType(n.get("right"), resolveField, isIntStoredEnum); List errors = new ArrayList<>(l.errors); errors.addAll(r.errors); if (l.type != null && !FilterOps.opsForSubType(l.type).contains(op)) { @@ -516,7 +742,7 @@ public static InferResult inferExprType(Object node, Function re } if (NULL_OPS.contains(op)) { return new InferResult(BooleanField.SUBTYPE_BOOLEAN, - inferExprType(n.get("arg"), resolveField).errors); + inferExprType(n.get("arg"), resolveField, isIntStoredEnum).errors); } if (EXPR_OP_NOT.equals(op) || VARIADIC_LOGIC_OPS.contains(op)) { List kids = new ArrayList<>(); @@ -524,7 +750,7 @@ public static InferResult inferExprType(Object node, Function re else for (Object a : (List) n.get("args")) kids.add(a); List errors = new ArrayList<>(); for (Object k : kids) { - InferResult kt = inferExprType(k, resolveField); + InferResult kt = inferExprType(k, resolveField, isIntStoredEnum); errors.addAll(kt.errors); if (kt.type != null && !BooleanField.SUBTYPE_BOOLEAN.equals(kt.type)) { errors.add("op '" + op + "' requires boolean operands, got " + kt.type); diff --git a/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java b/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java index 7a155cd73f..07e08dbc75 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java +++ b/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java @@ -86,7 +86,7 @@ public final class CanonicalJsonSerializer { * Plain Gson (no pretty-printing) — pretty-printing is applied by * {@link #toCanonicalString} over the full tree, not per-attribute. */ - private static final Gson GSON = new Gson(); + private static final Gson GSON = new GsonBuilder().serializeNulls().create(); /** Prefix for inline @-attributes. */ private static final String ATTR_PREFIX = "@"; @@ -877,6 +877,7 @@ private static JsonElement primitiveToJson(Object value) { */ private static String toCanonicalString(JsonElement element) { String raw = new GsonBuilder() + .serializeNulls() // a null literal in an expression tree ({ value: null }) is content .setPrettyPrinting() .disableHtmlEscaping() .create() diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 8f0df29b6f..89673d1c49 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -51,8 +51,10 @@ import com.metaobjects.origin.AggregateOrigin; import com.metaobjects.origin.ComputedOrigin; import com.metaobjects.origin.FirstOrigin; +import com.metaobjects.origin.FunctionOrigin; import com.metaobjects.origin.MetaOrigin; import com.metaobjects.origin.PassthroughOrigin; +import com.metaobjects.origin.ViewExpressionsTypesMetaDataProvider; import com.metaobjects.relationship.M2MFields; import com.metaobjects.relationship.MetaRelationship; import com.metaobjects.relationship.RelationshipReferences; @@ -282,6 +284,8 @@ public static void run(MetaRoot root, MetaDataLoader loader) { pass(collected, () -> validateDataGridLayouts(root)); // #207 — projection row-scope @filter field-ref validation (fail-closed). pass(collected, () -> validateProjectionFilter(root)); + // rc.21 part B — @union / @grain / @grainOrdinal shape rules on object.projection. + pass(collected, () -> collected.addAll(validateProjectionUnionAndGrain(root))); // Origin @segment names a segment of the related entity; a correlated @filter operand // names a base-row field. pass(collected, () -> validateOriginSegmentsAndCorrelation(root)); @@ -2581,6 +2585,14 @@ private static String conditionProblem(Object condition, java.util.Map fields.containsKey(name) ? fields.get(name).getSubType() : null); if (!inferred.errors.isEmpty()) { @@ -2688,8 +2700,8 @@ private static void collectExprFieldRefs(Object node, java.util.Set out) private static List> exprNodes(Object node, List> out) { if (node instanceof java.util.Map m) { out.add(m); - for (String k : List.of("left", "right", "arg", ExpressionAttribute.EXPR_CASE_OPERAND, - ExpressionAttribute.EXPR_CASE_ELSE)) exprNodes(m.get(k), out); + for (String k : List.of("left", "right", "arg", ExpressionAttribute.EXPR_CAST, + ExpressionAttribute.EXPR_CASE_OPERAND, ExpressionAttribute.EXPR_CASE_ELSE)) exprNodes(m.get(k), out); if (m.get("args") instanceof java.util.Collection args) for (Object a : args) exprNodes(a, out); if (m.get(ExpressionAttribute.EXPR_CASE) instanceof java.util.Collection arms) { for (Object arm : arms) { @@ -2703,6 +2715,228 @@ private static void collectExprFieldRefs(Object node, java.util.Set out) return out; } + /** + * rc.21 part B (U10) — origin.function: a call of a database function the project owns. Its name + * and schema are plain identifiers (never free SQL); each argument names a scalar field of the + * host (an entity), or of the projection (not an aggregate, not the field itself) or its base. + * Mirrors TS {@code _validateFunctionOrigin}. + */ + private static void validateFunctionOrigin(MetaOrigin origin, MetaObject obj, MetaField field, MetaRoot root) { + com.metaobjects.source.ErrorSource src = origin.getSource(); + String where = "origin.function on " + obj.getName() + "." + field.getName(); + // ADR-0039: own — origin.* never inherits (ADR-0029). + for (String attr : List.of(FunctionOrigin.ATTR_FUNCTION, FunctionOrigin.ATTR_SCHEMA)) { + if (!origin.hasMetaAttr(attr, false)) continue; + String v = origin.getMetaAttr(attr, false).getValueAsString(); + if (v == null || !FunctionOrigin.IDENTIFIER.matcher(v).matches()) { + throw invalidOrigin(where + ": @" + attr + " \"" + v + "\" is not a plain identifier" + + " ([A-Za-z_][A-Za-z0-9_]*); a function is named, never written as SQL.", src); + } + } + List args = originStringList(origin, FunctionOrigin.ATTR_ARGS); + // The declared signature: each parameter and the result is a field subtype (the cast targets); + // the result is the carrying field's, each argument its parameter's. + List params = originStringList(origin, FunctionOrigin.ATTR_PARAMS); + List types = new ArrayList<>(params); + List returned = originStringList(origin, FunctionOrigin.ATTR_RETURNS); + types.addAll(returned); + for (String t : types) { + if (!ExpressionAttribute.EXPR_CAST_TARGETS.contains(t)) { + throw invalidOrigin(where + ": \"" + t + "\" is not a parameter or return type; use one of " + + String.join(", ", ExpressionAttribute.EXPR_CAST_TARGETS) + ".", src); + } + } + if (!returned.isEmpty() && !returned.get(0).equals(field.getSubType())) { + throw invalidOrigin(where + ": @returns " + returned.get(0) + ", but the field is field." + + field.getSubType() + "; the declared return type must be the field's type.", src); + } + if (params.size() != args.size()) { + throw invalidOrigin(where + ": @params declares " + params.size() + " parameter type(s) for " + + args.size() + " argument(s); declare one per @args entry.", src); + } + boolean isProjection = MetaObject.SUBTYPE_PROJECTION.equals(obj.getSubType()); + MetaObject base = isProjection ? deriveBaseEntityOrNull(obj, root, field.getName(), src) : obj; + for (int index = 0; index < args.size(); index++) { + String name = args.get(index); + MetaField own = null; + if (!name.equals(field.getShortName())) { + for (MetaField f : obj.getChildren(MetaField.class, true)) { + if (name.equals(f.getShortName())) { own = f; break; } + } + } + MetaOrigin ownOrigin = own == null ? null : ownOriginOf(own); + MetaField arg = own; + if (arg == null && base != null) { + for (MetaField f : base.getChildren(MetaField.class, true)) { + if (name.equals(f.getShortName())) { arg = f; break; } + } + } + if (arg == null || name.equals(field.getShortName())) { + throw invalidOrigin(where + ": @args names \"" + name + "\", which is not a field of " + + (isProjection ? "the projection or its base entity" : "\"" + obj.getName() + "\"") + ".", src); + } else if (ownOrigin != null && AggregateOrigin.SUBTYPE_AGGREGATE.equals(ownOrigin.getSubType())) { + throw invalidOrigin(where + ": @args names \"" + name + "\", an origin.aggregate; a function" + + " takes values of the row, not of the group.", src); + } else if (ObjectField.SUBTYPE_OBJECT.equals(arg.getSubType()) || MapField.SUBTYPE_MAP.equals(arg.getSubType()) + || arg.isArrayType()) { + throw invalidOrigin(where + ": @args names \"" + name + "\", a field." + arg.getSubType() + + (arg.isArrayType() ? " array" : "") + "; a function argument is a scalar.", src); + } else if (!arg.getSubType().equals(params.get(index))) { + throw invalidOrigin(where + ": argument " + (index + 1) + " \"" + name + "\" is a field." + + arg.getSubType() + ", but parameter " + (index + 1) + " is declared " + params.get(index) + + "; pass an origin.computed field that casts it ({ cast: { field: " + name + " }, as: " + + params.get(index) + " }).", src); + } + } + } + + /** rc.21 part B (U14): the value object a {@code @grain} projection's rows are elements of, if it has one. */ + private static MetaObject grainValueObject(MetaObject obj, MetaRoot root) { + // ADR-0039: own — a projection's @grain names ITS view's shape; an extender declares its own. + if (!MetaObject.SUBTYPE_PROJECTION.equals(obj.getSubType()) + || !obj.hasMetaAttr(ViewExpressionsTypesMetaDataProvider.ATTR_GRAIN, false)) return null; + String grain = obj.getMetaAttr(ViewExpressionsTypesMetaDataProvider.ATTR_GRAIN, false).getValueAsString(); + MetaObject base = deriveBaseEntityOrNull(obj, root, "@grain", obj.getSource()); + if (base == null) return null; + for (MetaField f : base.getChildren(MetaField.class, true)) { + if (f.getShortName().equals(grain)) return References.refTarget(f, ObjectField.ATTR_OBJECTREF); + } + return null; + } + + /** An own string or string-array attr of a node, one entry per item; empty when absent. */ + private static List ownStringList(MetaData node, String attr) { + if (!node.hasMetaAttr(attr, false)) return java.util.Collections.emptyList(); + Object raw = node.getMetaAttr(attr, false).getValue(); + List out = new ArrayList<>(); + if (raw instanceof Iterable items) { + for (Object o : items) out.add(String.valueOf(o)); + } else if (raw != null) { + out.add(String.valueOf(raw)); + } + return out; + } + + /** + * rc.21 part B — the projection shapes beside a plain view: + *
    + *
  • {@code @union} names projections whose rows join this one's: each must be an + * object.projection other than this one, with the same effective fields in order (name, + * subtype, array-ness and {@code @column}); {@code @unionAll} needs {@code @union};
  • + *
  • {@code @grain} names a base-entity field.object array stored as jsonb; such a projection + * holds no origin.aggregate, and {@code @grainOrdinal} names one of its own field.int / + * field.long fields with no origin.
  • + *
+ * ERR_BAD_ATTR_VALUE otherwise. Mirrors TS {@code validateProjectionUnionAndGrain}. + */ + static List validateProjectionUnionAndGrain(MetaRoot root) { + List errors = new ArrayList<>(); + for (MetaObject obj : rootObjects(root)) { + if (!MetaObject.SUBTYPE_PROJECTION.equals(obj.getSubType())) continue; + java.util.function.Consumer bad = message -> errors.add(new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": object.projection " + obj.getName() + ": " + message, + ErrorCode.ERR_BAD_ATTR_VALUE, obj.getSource())); + String unionAttr = ViewExpressionsTypesMetaDataProvider.ATTR_UNION; + String unionAllAttr = ViewExpressionsTypesMetaDataProvider.ATTR_UNION_ALL; + // ADR-0039: own — a projection's @union, @grain names ITS view's shape; an extender declares its own. + boolean hasUnion = obj.hasMetaAttr(unionAttr, false); + if (obj.hasMetaAttr(unionAllAttr, false) && !hasUnion) { + bad.accept("@" + unionAllAttr + " needs @" + unionAttr + "."); + } + if (hasUnion) { + String referrerPkg = obj.getPackage() == null ? "" : obj.getPackage(); + List a = new ArrayList<>(); + for (MetaField f : obj.getChildren(MetaField.class, true)) a.add(describeUnionField(f)); + for (String name : ownStringList(obj, unionAttr)) { + MetaObject member = resolveRootObject(root, name, referrerPkg); + if (member == null || !MetaObject.SUBTYPE_PROJECTION.equals(member.getSubType())) { + bad.accept("@" + unionAttr + " names \"" + name + "\", which is not an object.projection."); + continue; + } + if (member == obj) { + bad.accept("@" + unionAttr + " names the projection itself."); + continue; + } + // A member's own @union would be flattened away, silently. + if (member.hasMetaAttr(unionAttr, false)) { + bad.accept("@" + unionAttr + " member \"" + member.getName() + "\" declares its own @" + + unionAttr + "; name its members here instead."); + } + List b = new ArrayList<>(); + for (MetaField f : member.getChildren(MetaField.class, true)) b.add(describeUnionField(f)); + if (!a.equals(b)) { + bad.accept("@" + unionAttr + " member \"" + member.getName() + "\" has a different shape: (" + + String.join(", ", b) + ") where this view is (" + String.join(", ", a) + + "). A union's members have the same fields, in order."); + } + } + } + String grainAttr = ViewExpressionsTypesMetaDataProvider.ATTR_GRAIN; + String ordinalAttr = ViewExpressionsTypesMetaDataProvider.ATTR_GRAIN_ORDINAL; + boolean hasGrain = obj.hasMetaAttr(grainAttr, false); + boolean hasOrdinal = obj.hasMetaAttr(ordinalAttr, false); + if (hasOrdinal && !hasGrain) bad.accept("@" + ordinalAttr + " needs @" + grainAttr + "."); + if (!hasGrain) continue; + String grain = obj.getMetaAttr(grainAttr, false).getValueAsString(); + MetaObject base = deriveBaseEntityOrNull(obj, root, "@grain", obj.getSource()); + MetaField grainField = null; + if (base != null) { + for (MetaField f : base.getChildren(MetaField.class, true)) { + if (f.getShortName().equals(grain)) { grainField = f; break; } + } + } + boolean storageOk = grainField != null && (!grainField.hasMetaAttr(MetaField.ATTR_STORAGE) + || "jsonb".equals(grainField.getMetaAttr(MetaField.ATTR_STORAGE).getValueAsString())); + if (grainField == null || !ObjectField.SUBTYPE_OBJECT.equals(grainField.getSubType()) + || !grainField.isArrayType() || !storageOk + || References.refTarget(grainField, ObjectField.ATTR_OBJECTREF) == null) { + bad.accept("@" + grainAttr + " \"" + grain + "\" must name a field.object array (isArray, jsonb storage," + + " with @objectRef) of the base entity" + (base == null ? "" : " \"" + base.getName() + "\"") + "."); + } + for (MetaField f : obj.getChildren(MetaField.class, true)) { + MetaOrigin o = ownOriginOf(f); + if (o != null && AggregateOrigin.SUBTYPE_AGGREGATE.equals(o.getSubType())) { + bad.accept("\"" + f.getShortName() + "\" is an origin.aggregate; a @grain view has one row per" + + " element and groups nothing."); + } + } + if (hasOrdinal) { + String ordinal = obj.getMetaAttr(ordinalAttr, false).getValueAsString(); + MetaField f = null; + for (MetaField c : obj.getChildren(MetaField.class, true)) { + if (c.getShortName().equals(ordinal)) { f = c; break; } + } + if (f == null || !(IntegerField.SUBTYPE_INT.equals(f.getSubType()) || LongField.SUBTYPE_LONG.equals(f.getSubType())) + || ownOriginOf(f) != null || f.getSuperData() != null) { + bad.accept("@" + ordinalAttr + " \"" + ordinal + "\" must name a field.int or field.long of the" + + " projection, with no origin and no extends."); + } + } + } + return errors; + } + + /** One union column as a comparable string: name, subtype, array-ness, @column and an enum's members and value maps. */ + private static String describeUnionField(MetaField f) { + StringBuilder sb = new StringBuilder(f.getShortName()).append(": field.").append(f.getSubType()); + if (f.isArrayType()) sb.append("[]"); + if (f.hasMetaAttr(MetaField.ATTR_COLUMN)) sb.append(" @column ").append(f.getMetaAttr(MetaField.ATTR_COLUMN).getValueAsString()); + if (EnumField.SUBTYPE_ENUM.equals(f.getSubType())) { + // An enum's members and value maps are part of the column's meaning. + List shape = new ArrayList<>(); + for (String a : List.of(EnumField.ATTR_VALUES, EnumField.ATTR_INT_VALUE_MAP, EnumField.ATTR_STRING_VALUE_MAP)) { + shape.add(f.hasMetaAttr(a) ? f.getMetaAttr(a).getValue() : null); + } + sb.append(' ').append(new com.google.gson.Gson().toJson(shape)); + } + return sb.toString(); + } + + private static MetaDataException invalidOrigin(String message, com.metaobjects.source.ErrorSource src) { + return new MetaDataException(ErrorMessageConstants.ERR_INVALID_ORIGIN + ": " + message, + ErrorCode.ERR_INVALID_ORIGIN, src); + } + /** A field's origin. ADR-0039: own — origin.* never inherits (ADR-0029), so it is declared on the field. */ private static MetaOrigin ownOriginOf(MetaField field) { for (MetaData oc : field.getChildren(MetaData.class, false)) { @@ -3149,6 +3383,31 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, } OriginTarget fromTarget = validateFromOrOfPath(from, root, obj, field.getName(), "origin.passthrough.@from", origin.getSource()); + // rc.21 part B (U14): on a @grain projection, a @from on the grain field's value object + // reads a member of the array element; there is no path to walk. + if (fromTarget.entity != null && fromTarget.entity == grainValueObject(obj, root)) { + checkPassthroughType(field, fromTarget.field, from, origin.isConvert(), obj, origin.getSource()); + MetaField member = fromTarget.field; + if (member.isArrayType() || ObjectField.SUBTYPE_OBJECT.equals(member.getSubType()) + || MapField.SUBTYPE_MAP.equals(member.getSubType())) { + throw invalidOrigin("origin.passthrough on " + obj.getName() + "." + field.getName() + ": @from \"" + + from + "\" is not a scalar member of the @grain element.", origin.getSource()); + } + String grainVia = origin.getVia(); + if (grainVia != null && !grainVia.isEmpty()) { + throw invalidOrigin("origin.passthrough on " + obj.getName() + "." + field.getName() + ": @from \"" + + from + "\" reads the @grain element, which takes no @via.", origin.getSource()); + } + // A value object's enum member is held in the document as its symbol; a value map + // describes a column the element does not have. + if (EnumField.SUBTYPE_ENUM.equals(member.getSubType()) + && (member.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP) || member.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP))) { + throw invalidOrigin("origin.passthrough on " + obj.getName() + "." + field.getName() + ": @from \"" + + from + "\" is an enum with a value map, but a @grain element holds the member's symbol; " + + "read it as a field.string, or drop the map on the value object's member.", origin.getSource()); + } + return; + } // FR-024 B6 — extends/origin agreement (host-agnostic; before via/inference). checkExtendsOriginAgreement(field, fromTarget.field, from, obj, origin.getSource()); // #185 — passthrough is type-preserving unless @convert acknowledges a change @@ -3474,18 +3733,41 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, return; } } - ExpressionAttribute.InferResult inferred = ExpressionAttribute.inferExprType( - expr, name -> { - if (obj != baseEntity && !name.equals(selfName)) { - for (MetaField own : obj.getChildren(MetaField.class, true)) { - if (!name.equals(own.getShortName())) continue; - MetaOrigin ownOrigin = ownOriginOf(own); - if (ownOrigin != null - && AggregateOrigin.SUBTYPE_AGGREGATE.equals(ownOrigin.getSubType())) return null; - return own.getSubType(); - } + // rc.19 computed-over-joined: a ref names one of the projection's own fields first (a + // passthrough, an origin.first, another origin.computed or, rc.21 U13, a scalar + // origin.aggregate, read on the grouped row), else a base field, else (rc.21 U3, a + // projection only) a PATH of to-one hops from the base and a field of the entity + // reached, joined but not output. Never itself; never a collect (an array). + java.util.function.Function> fieldNode = name -> { + if (obj != baseEntity && !name.equals(selfName)) { + for (MetaField own : obj.getChildren(MetaField.class, true)) { + if (name.equals(own.getShortName())) return own; } - return resolvedFieldSubType(baseEntity, name); + } + MetaField baseField = null; + for (MetaData c : baseEntity.getChildren(MetaData.class, true)) { + if (c instanceof MetaField f && nameMatches(c, name)) { baseField = f; break; } + } + if (baseField != null || obj == baseEntity || !name.contains(".")) return baseField; + com.metaobjects.relationship.FilterPath.Result path = + com.metaobjects.relationship.FilterPath.resolve(baseEntity, name); + return path != null && path.path() != null ? path.path().field() : null; + }; + java.util.function.Function> refNode = name -> { + MetaField node = fieldNode.apply(name); + if (node == null) return null; + MetaOrigin nodeOrigin = ownOriginOf(node); + if (!name.equals(selfName) && nodeOrigin != null + && AggregateOrigin.SUBTYPE_AGGREGATE.equals(nodeOrigin.getSubType()) + && MetaOrigin.AGG_COLLECT.equals(nodeOrigin.getAgg())) return null; + return node; + }; + ExpressionAttribute.InferResult inferred = ExpressionAttribute.inferExprType( + expr, name -> { MetaField n = refNode.apply(name); return n == null ? null : n.getSubType(); }, + name -> { + MetaField n = fieldNode.apply(name); + return n != null && EnumField.SUBTYPE_ENUM.equals(n.getSubType()) + && n.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP); }); if (!inferred.errors.isEmpty()) { throw new MetaDataException( @@ -3497,21 +3779,7 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, // A literal compared with a field must be able to equal it: of its kind, and for an // enum one of its @values (the rule a validator's @condition follows). Resolved as the // inference resolved the ref: a projection field first, else a base field. - String literalProblem = literalComparisonProblem(expr, name -> { - if (obj != baseEntity && !name.equals(selfName)) { - for (MetaField own : obj.getChildren(MetaField.class, true)) { - if (!name.equals(own.getShortName())) continue; - MetaOrigin ownOrigin = ownOriginOf(own); - if (ownOrigin != null - && AggregateOrigin.SUBTYPE_AGGREGATE.equals(ownOrigin.getSubType())) return null; - return own; - } - } - for (MetaData c : baseEntity.getChildren(MetaData.class, true)) { - if (c instanceof MetaField f && nameMatches(c, name)) return f; - } - return null; - }); + String literalProblem = literalComparisonProblem(expr, refNode); if (literalProblem != null) { throw new MetaDataException( ErrorMessageConstants.ERR_INVALID_ORIGIN @@ -3531,6 +3799,12 @@ private static void validateOriginNode(MetaRoot root, MetaObject obj, return; } + // origin.function — rc.21 part B (U10): a call of a database function the project owns. + if (FunctionOrigin.SUBTYPE_FUNCTION.equals(subType)) { + validateFunctionOrigin(origin, obj, field, root); + return; + } + // origin.first — #195: pick one related row by @orderBy along @via, project @of. if (FirstOrigin.SUBTYPE_FIRST.equals(subType)) { com.metaobjects.source.ErrorSource src = origin.getSource(); @@ -4193,7 +4467,8 @@ static void validateOriginSegmentsAndCorrelation(MetaRoot root) { Object filter = origin.getMetaAttr(MetaOrigin.ATTR_FILTER, false).getValue(); MetaObject base = deriveBaseEntityOrNull(obj, root, field.getName(), origin.getSource()); if (base == null) continue; - checkCorrelatedOperands(filter, base, where, origin.getSource()); + checkCorrelatedOperands(filter, base, where, origin.getSource(), + MetaObject.SUBTYPE_PROJECTION.equals(obj.getSubType())); } } } @@ -4242,13 +4517,13 @@ private static MetaObject originRelatedEntity(MetaOrigin origin, MetaObject obj, } private static void checkCorrelatedOperands(Object filter, MetaObject base, String where, - com.metaobjects.source.ErrorSource source) { + com.metaobjects.source.ErrorSource source, boolean onProjection) { if (!(filter instanceof java.util.Map m)) return; for (java.util.Map.Entry e : m.entrySet()) { String key = String.valueOf(e.getKey()); if ("and".equals(key) || "or".equals(key)) { if (e.getValue() instanceof Iterable subs) { - for (Object sub : subs) checkCorrelatedOperands(sub, base, where, source); + for (Object sub : subs) checkCorrelatedOperands(sub, base, where, source, onProjection); } continue; } @@ -4284,10 +4559,23 @@ private static void checkCorrelatedOperands(Object filter, MetaObject base, Stri } } if (!known) { + // rc.21 part B (U4): on a projection, the operand may be a PATH of to-one hops from + // the base row and a field of the entity reached ("orderId.customerId"), joined on + // the outer row. + com.metaobjects.relationship.FilterPath.Result path = + name instanceof String ns && ns.contains(".") && onProjection + ? com.metaobjects.relationship.FilterPath.resolve(base, ns) : null; + if (path != null && path.path() != null) continue; + String why = path != null + ? "compares with the base-row path \"" + name + "\": " + path.error() + "." + : name instanceof String ns2 && ns2.contains(".") && !onProjection + ? "compares with the path \"" + name + "\"; a path operand is legal only on a projection," + + " whose view joins it." + : "names base-row field \"" + name + "\", which \"" + base.getShortName() + + "\" does not declare."; throw new MetaDataException( ErrorMessageConstants.ERR_BAD_ATTR_FILTER + ": " + where + ": @filter on \"" + key - + "\" names base-row field \"" + name + "\", which \"" + base.getShortName() - + "\" does not declare.", + + "\" " + why, ErrorCode.ERR_BAD_ATTR_FILTER, source); } } @@ -5839,7 +6127,8 @@ static void validateDerivedFieldProvidability(MetaRoot root) { // A derived field a projection reaches (its @filter or a passthrough @from) // is lowered inline there, so it needs no read source. Only the inlinable origins. if ((FirstOrigin.SUBTYPE_FIRST.equals(origin.getSubType()) - || ComputedOrigin.SUBTYPE_COMPUTED.equals(origin.getSubType())) + || ComputedOrigin.SUBTYPE_COMPUTED.equals(origin.getSubType()) + || FunctionOrigin.SUBTYPE_FUNCTION.equals(origin.getSubType())) && reached.contains(fc)) { continue; } @@ -5896,11 +6185,54 @@ static java.util.Set projectionReachedEntityFields(MetaRoot root) { // The origin pass reports an unresolved @from. } } + // rc.21 part B (U3): a computed expression's path ref reaches the field at its end. + MetaOrigin computed = ownOriginOf(field); + if (computed != null && ComputedOrigin.SUBTYPE_COMPUTED.equals(computed.getSubType()) + && base != null && base != obj && computed.hasMetaAttr(MetaOrigin.ATTR_EXPR, false)) { + java.util.Set refs = new java.util.LinkedHashSet<>(); + collectExprFieldRefs(computed.getMetaAttr(MetaOrigin.ATTR_EXPR, false).getValue(), refs); + for (String name : refs) { + if (!name.contains(".")) continue; + com.metaobjects.relationship.FilterPath.Result path = + com.metaobjects.relationship.FilterPath.resolve(base, name); + if (path != null && path.path() != null) reached.add(path.path().field()); + } + } } } + // A reached origin.function inlines its arguments on the same row, so a derived argument + // (an origin.computed cast, say) is reached too. + for (MetaData f : new java.util.ArrayList<>(reached)) reachFunctionArgs(f, reached); return reached; } + private static void reachFunctionArgs(MetaData f, java.util.Set reached) { + MetaOrigin origin = f instanceof MetaField mf ? ownOriginOf(mf) : null; + MetaData host = f.getParent(); + if (origin == null || !FunctionOrigin.SUBTYPE_FUNCTION.equals(origin.getSubType()) || host == null) return; + for (String name : originStringList(origin, FunctionOrigin.ATTR_ARGS)) { + for (MetaData c : host.getChildren(MetaData.class, true)) { + if (c instanceof MetaField && name.equals(c.getShortName())) { + if (reached.add(c)) reachFunctionArgs(c, reached); + break; + } + } + } + } + + /** An origin's own string-array attr ({@code @args}, {@code @params}), one entry per item. */ + private static List originStringList(MetaOrigin origin, String attr) { + if (!origin.hasMetaAttr(attr, false)) return java.util.Collections.emptyList(); + Object raw = origin.getMetaAttr(attr, false).getValue(); + List out = new ArrayList<>(); + if (raw instanceof Iterable items) { + for (Object o : items) out.add(String.valueOf(o)); + } else if (raw != null) { + out.add(String.valueOf(raw)); + } + return out; + } + // ========================================================================= // FR-037 R1 — field-level @mutability cross-attribute rules. // ERR_MUTABILITY_AUTOSET_CONFLICT / ERR_MUTABILITY_DOWNGRADE / diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java index 533e68aa68..660cddf909 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java @@ -21,8 +21,8 @@ /** * rc.21 part B (U10) — {@code origin.function}: a value computed by a database function the * project owns, named ({@code @function}, {@code @schema}) and typed by its argument fields - * ({@code @args}). Registered so a strict load accepts it; the call rules run in TypeScript - * and C#, and only the TypeScript view emitter lowers it. + * ({@code @args}). Registered so a strict load accepts it; the call rules run in the loader + * (ValidationPhase), and only the TypeScript view emitter lowers it. */ public class FunctionOrigin extends MetaOrigin { @@ -33,6 +33,8 @@ public class FunctionOrigin extends MetaOrigin { public static final String ATTR_ARGS = "args"; public static final String ATTR_PARAMS = "params"; public static final String ATTR_RETURNS = "returns"; + /** A function and a schema name are plain identifiers, never free SQL. */ + public static final java.util.regex.Pattern IDENTIFIER = java.util.regex.Pattern.compile("^[A-Za-z_][A-Za-z0-9_]*$"); public FunctionOrigin(String name) { super(SUBTYPE_FUNCTION, name); diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/ViewExpressionsTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/origin/ViewExpressionsTypesMetaDataProvider.java index e55e087708..572faea989 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/ViewExpressionsTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/ViewExpressionsTypesMetaDataProvider.java @@ -36,6 +36,12 @@ public class ViewExpressionsTypesMetaDataProvider implements MetaDataTypeProvide /** The pack's cross-port logical id, the {@code provider} of view-expressions.json. */ public static final String LOGICAL_ID = "metaobjects-view-expressions"; + /** The projection attrs this pack adds (names as in {@code spec/metamodel/view-expressions.json}). */ + public static final String ATTR_UNION = "union"; + public static final String ATTR_UNION_ALL = "unionAll"; + public static final String ATTR_GRAIN = "grain"; + public static final String ATTR_GRAIN_ORDINAL = "grainOrdinal"; + @Override public void registerTypes(MetaDataRegistry registry) { FunctionOrigin.registerTypes(registry); diff --git a/server/java/metadata/src/test/java/com/metaobjects/attr/ExpressionViewVocabularyTest.java b/server/java/metadata/src/test/java/com/metaobjects/attr/ExpressionViewVocabularyTest.java new file mode 100644 index 0000000000..9438610d16 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/attr/ExpressionViewVocabularyTest.java @@ -0,0 +1,200 @@ +package com.metaobjects.attr; + +import com.google.gson.Gson; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * The rc.21 view vocabulary of the expression grammar: the typed function set, {@code cast}, + * the cast legality table and the {@code dbColumnType} spelling rules. Mirrors the TypeScript + * reference ({@code meta-attr-expression.ts}); the shared fixtures pin the same behaviour. + */ +public class ExpressionViewVocabularyTest { + + private static final Gson GSON = new Gson(); + + private static final Map FIELDS = Map.ofEntries( + Map.entry("s", "string"), Map.entry("i", "int"), Map.entry("l", "long"), Map.entry("d", "decimal"), + Map.entry("b", "boolean"), Map.entry("e", "enum"), Map.entry("ie", "enum"), Map.entry("o", "object"), + Map.entry("ts", "timestamp"), Map.entry("dt", "date"), Map.entry("u", "uuid")); + + @SuppressWarnings("unchecked") + private static Map expr(String json) { + return (Map) GSON.fromJson(json, Map.class); + } + + private static final Function RESOLVE = FIELDS::get; + + private static List infer(String json) { + return ExpressionAttribute.inferExprType(expr(json), RESOLVE, name -> name.equals("ie")).errors; + } + + private static String type(String json) { + return ExpressionAttribute.inferExprType(expr(json), RESOLVE, name -> name.equals("ie")).type; + } + + private static String fn(String name, String... args) { + return "{\"fn\":\"" + name + "\",\"args\":[" + String.join(",", args) + "]}"; + } + + private static final String S = "{\"field\":\"s\"}"; + private static final String I = "{\"field\":\"i\"}"; + private static final String L = "{\"field\":\"l\"}"; + + // --- structural arity ------------------------------------------------ + + @Test + public void everyFunctionIsRegisteredAndUnknownOnesAreRefused() { + assertEquals(15, ExpressionAttribute.EXPR_FUNCTIONS.size()); + assertEquals(List.of("unknown expression fn 'drop'"), + ExpressionAttribute.validateExprNode(expr(fn("drop", S)))); + } + + @Test + public void arityErrorsNameTheFunction() { + assertEquals(List.of("'lower' takes at most 1 args, got 2"), + ExpressionAttribute.validateExprNode(expr(fn("lower", S, S)))); + assertEquals(List.of("'splitPart' requires at least 3 args"), + ExpressionAttribute.validateExprNode(expr(fn("splitPart", S, S)))); + assertEquals(List.of("'nullif' requires at least 2 args"), + ExpressionAttribute.validateExprNode(expr(fn("nullif", S)))); + assertEquals(List.of("'coalesce' requires a non-empty args array"), + ExpressionAttribute.validateExprNode(expr("{\"fn\":\"coalesce\",\"args\":[]}"))); + assertEquals(List.of("'btrim' takes at most 2 args, got 3"), + ExpressionAttribute.validateExprNode(expr(fn("btrim", S, S, S)))); + assertTrue(ExpressionAttribute.validateExprNode(expr(fn("concat", S, I, L, S))).isEmpty()); + } + + // --- parameter kinds and results ------------------------------------- + + @Test + public void stringParametersRefuseOtherTypes() { + assertEquals(List.of("'lower' argument 1 must be a string, got int"), infer(fn("lower", I))); + assertEquals("string", type(fn("upper", S))); + assertEquals(List.of("'replace' argument 3 must be a string, got int"), infer(fn("replace", S, S, I))); + } + + @Test + public void intParametersRefuseLongWithACastHint() { + assertEquals("string", type(fn("splitPart", S, S, I))); + assertEquals( + List.of("'left' argument 2 must be an int, got long; cast it ({ cast: , as: int })"), + infer(fn("left", S, L))); + assertEquals(List.of("'substring' argument 3 must be an int, got string"), + infer(fn("substring", S, I, S))); + assertEquals("int", type(fn("length", S))); + } + + @Test + public void scalarParametersRefuseObjects() { + assertEquals("string", type(fn("concat", S, I, "{\"field\":\"b\"}"))); + assertEquals(List.of("'concat' argument 2 must be a scalar, got object"), + infer(fn("concat", S, "{\"field\":\"o\"}"))); + assertEquals(List.of("'concatWs' argument 1 must be a string, got int"), + infer(fn("concatWs", I, S))); + } + + @Test + public void sameParametersUnifyAndOrderedOnesRefuseBooleans() { + assertEquals("int", type(fn("greatest", I, "{\"value\":3}"))); + assertEquals(List.of("'nullif' arguments have differing types (string, int)"), infer(fn("nullif", S, I))); + assertEquals(List.of("'greatest' needs ordered arguments, got boolean"), + infer(fn("greatest", "{\"field\":\"b\"}", "{\"field\":\"b\"}"))); + assertEquals("boolean", type(fn("coalesce", "{\"field\":\"b\"}", "{\"value\":true}"))); + // A null literal fits any parameter. + assertEquals("string", type(fn("nullif", S, "{\"value\":null}"))); + } + + // --- cast ------------------------------------------------------------ + + @Test + public void castLegalityTableMatchesTheReference() { + assertNull(ExpressionAttribute.castProblem(null, "int", false)); + assertNull(ExpressionAttribute.castProblem("int", "int", false)); + assertEquals("a field.object value cannot be cast", ExpressionAttribute.castProblem("object", "string", false)); + assertEquals("a field.map value cannot be cast", ExpressionAttribute.castProblem("map", "string", false)); + // anything to string, string to anything + assertNull(ExpressionAttribute.castProblem("boolean", "string", false)); + assertNull(ExpressionAttribute.castProblem("uuid", "string", false)); + assertNull(ExpressionAttribute.castProblem("string", "uuid", false)); + // numbers among themselves; a boolean only to int + assertNull(ExpressionAttribute.castProblem("currency", "decimal", false)); + assertNull(ExpressionAttribute.castProblem("boolean", "int", false)); + assertEquals("a boolean casts only to int, not long", ExpressionAttribute.castProblem("boolean", "long", false)); + assertEquals("a date cannot be cast to int", ExpressionAttribute.castProblem("date", "int", false)); + assertNull(ExpressionAttribute.castProblem("int", "boolean", false)); + assertEquals("a long cannot be cast to boolean; only an int can", ExpressionAttribute.castProblem("long", "boolean", false)); + // temporal + assertNull(ExpressionAttribute.castProblem("date", "timestamp", false)); + assertNull(ExpressionAttribute.castProblem("timestamp", "date", false)); + assertEquals("a int cannot be cast to date", ExpressionAttribute.castProblem("int", "date", false)); + assertEquals("a uuid cannot be cast to int", ExpressionAttribute.castProblem("uuid", "int", false)); + } + + @Test + public void intStoredEnumCastsToIntegersNotToString() { + assertNull(ExpressionAttribute.castProblem("enum", "string", false)); + assertEquals("an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int", + ExpressionAttribute.castProblem("enum", "string", true)); + assertNull(ExpressionAttribute.castProblem("enum", "int", true)); + assertNull(ExpressionAttribute.castProblem("enum", "long", true)); + assertEquals("only an enum stored as an integer (@intValueMap) can be cast to a number", + ExpressionAttribute.castProblem("enum", "int", false)); + assertEquals("an enum cannot be cast to decimal", ExpressionAttribute.castProblem("enum", "decimal", true)); + + assertEquals("int", type("{\"cast\":{\"field\":\"ie\"},\"as\":\"int\"}")); + assertTrue(infer("{\"cast\":{\"field\":\"ie\"},\"as\":\"int\"}").isEmpty()); + assertEquals(List.of("'cast': only an enum stored as an integer (@intValueMap) can be cast to a number"), + infer("{\"cast\":{\"field\":\"e\"},\"as\":\"int\"}")); + } + + @Test + public void castOfANullLiteralTakesTheTargetType() { + assertEquals("string", type("{\"cast\":{\"value\":null},\"as\":\"string\",\"dbColumnType\":\"varchar\"}")); + } + + @Test + public void castShapeRules() { + assertTrue(ExpressionAttribute.validateExprNode(expr("{\"cast\":{\"field\":\"s\"},\"as\":\"uuid\"}")).isEmpty()); + assertEquals(1, ExpressionAttribute.validateExprNode(expr("{\"cast\":{\"field\":\"s\"},\"as\":\"object\"}")).size()); + assertEquals(1, ExpressionAttribute.validateExprNode(expr("{\"cast\":{\"field\":\"s\"}}")).size()); + assertEquals(List.of("expression 'cast' takes only 'as' and 'dbColumnType' beside it, not extra"), + ExpressionAttribute.validateExprNode(expr("{\"cast\":{\"field\":\"s\"},\"as\":\"int\",\"extra\":1}"))); + } + + @Test + public void castDbColumnTypeSpellings() { + for (String ok : List.of("text", "varchar", "character varying", "varchar(10)", "character varying(255)", "character(3)")) { + assertTrue(ok, ExpressionAttribute.validateExprNode( + expr("{\"cast\":{\"field\":\"i\"},\"as\":\"string\",\"dbColumnType\":\"" + ok + "\"}")).isEmpty()); + } + for (String bad : List.of("uuid", "jsonb", "VARCHAR", "varchar(0)", "char(3)", "varchar(10")) { + assertEquals(bad, 1, ExpressionAttribute.validateExprNode( + expr("{\"cast\":{\"field\":\"i\"},\"as\":\"string\",\"dbColumnType\":\"" + bad + "\"}")).size()); + } + // A spelling is a text type: only with as: string. + assertEquals(1, ExpressionAttribute.validateExprNode( + expr("{\"cast\":{\"field\":\"s\"},\"as\":\"int\",\"dbColumnType\":\"varchar\"}")).size()); + // And a non-string spelling is refused. + assertEquals(1, ExpressionAttribute.validateExprNode( + expr("{\"cast\":{\"field\":\"s\"},\"as\":\"string\",\"dbColumnType\":5}")).size()); + } + + // --- view-only nodes (the CHECK-condition subset) ---------------------- + + @Test + public void exprViewOnlyNodeFindsWhatACheckCannotHold() { + assertNull(ExpressionAttribute.exprViewOnlyNode(expr(fn("coalesce", S, "{\"value\":\"x\"}")))); + assertEquals("cast", ExpressionAttribute.exprViewOnlyNode(expr("{\"cast\":{\"field\":\"s\"},\"as\":\"int\"}"))); + assertEquals("lower", ExpressionAttribute.exprViewOnlyNode( + expr("{\"op\":\"eq\",\"left\":" + fn("lower", S) + ",\"right\":{\"value\":\"a\"}}"))); + assertEquals("the path \"a.b\"", ExpressionAttribute.exprViewOnlyNode(expr("{\"field\":\"a.b\"}"))); + } +} From f85ea621920846ce0ce6ac0d7939a88e6adf1ab0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 21:03:32 -0500 Subject: [PATCH 3/8] fix(metadata): keep quoted number-like text a string in the Java loader A quoted value on a string attribute (column: "007") was inferred as the integer 7. Quoted text is now never inferred, matching every other port, and the YAML conformance ledger is empty. Also records the C1 and C6 fixes in the changelog. --- CHANGELOG.md | 14 ++++++++++++++ docs/CONFORMANCE.md | 2 +- .../loader/parser/BaseMetaDataParser.java | 16 +++++++++++++++- .../loader/parser/json/CanonicalJsonParser.java | 3 ++- .../yaml-conformance-expected-failures.json | 5 +---- 5 files changed, 33 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db97cda069..144927c3c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2008,6 +2008,20 @@ Each item below is described in full under Security, Added, Changed or Fixed; th only a view can hold (a cast, a function other than `coalesce`, a dotted path). Python-written models are unaffected unless they used these nodes, which never loaded. +- **The Java and Kotlin loader accepts every view function and cast, not only `coalesce`.** Java + validated only `coalesce` inside a computed expression, so a model using `cast`, `lower`, + `concat`, `substring` and the rest of the function set, an `origin.function`, `@union` / + `@grain`, or a correlated filter that walks a reference was refused by the JVM ports while + TypeScript and C# loaded it. The Java loader now checks them the way TypeScript does (the + function arities and parameter kinds, the cast legality table, an int-stored enum cast, the + `dbColumnType` text spellings). The five conformance fixtures the Java ledger excused now + pass and its list is empty. No Java generator lowers these nodes to a view yet. +- **Quoted number-like text keeps its quotes in the Java loader.** A quoted value such as + `"007"` or `"true"` on a string attribute (`column: "007"`) was read as the integer `7` or the + boolean, so the canonical output differed from every other port. Quoted text is text; only an + unquoted number or boolean is inferred. The `yaml-quoted-leading-zero` fixture passes in Java + and the YAML ledger is empty. + - **A credential is never filterable or sortable, in every port.** A field that declares a `view.password` and that a model also marked `@filterable` or `@sortable` was on the generated filter and sort allowlists, so a client could learn its value by probing (`filter[pinHash][eq]=...`, diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 9aabdda1cd..0756a6e15f 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -27,7 +27,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| | [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 578 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | -| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 18 / 19 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | +| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | | [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 18 | ✓ | ✓ | inherits via Java | ✓ | ✓ | diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java index a08c550560..39674f3a2e 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java @@ -613,6 +613,17 @@ protected Object castStringValueToObject(String stringValue) { * Looks up the expected attribute definition from the parent's type definition */ protected void parseInlineAttribute(MetaData parentMetaData, String attrName, String stringValue) { + parseInlineAttribute(parentMetaData, attrName, stringValue, false); + } + + /** + * As {@link #parseInlineAttribute(MetaData, String, String)}, with {@code quotedText} set when + * the author wrote the value as a quoted string ({@code "007"}, {@code "true"}). Quoted text is + * text: the value-based type inference below is for unquoted numbers and booleans only, so a + * quoted number-like value keeps its quotes (every other port does the same). + */ + protected void parseInlineAttribute(MetaData parentMetaData, String attrName, String stringValue, + boolean quotedText) { try { // Special handling for isArray as native property (without @) if ("isArray".equals(attrName)) { @@ -642,7 +653,10 @@ protected void parseInlineAttribute(MetaData parentMetaData, String attrName, St } // If the registry returned "string" as default, try to infer a more specific type from the value - if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) { + // (never for quoted text: "007" is a string, not the integer 7). + if (quotedText) { + // keep "string" + } else if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) { expectedAttributeSubType = "boolean"; } else if (stringValue.matches("-?\\d+")) { // Check if value is within Integer range vs Long range diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java index 8a33e4e1b9..4c86219a63 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/json/CanonicalJsonParser.java @@ -1468,7 +1468,8 @@ private void processAttributes(MetaData md, JsonObject body) { } // Delegate to the base parser — handles type inference + array desugar - super.parseInlineAttribute(md, attrName, stringValue); + super.parseInlineAttribute(md, attrName, stringValue, + rawValue.isJsonPrimitive() && rawValue.getAsJsonPrimitive().isString()); // A bare string is ONE array element, commas included (TS // normalizeStringArrayAttr wraps "a,b" as ["a,b"]); the comma-delimited diff --git a/server/java/metadata/yaml-conformance-expected-failures.json b/server/java/metadata/yaml-conformance-expected-failures.json index 8116471ded..d65edffda8 100644 --- a/server/java/metadata/yaml-conformance-expected-failures.json +++ b/server/java/metadata/yaml-conformance-expected-failures.json @@ -1,8 +1,5 @@ { "language": "java", "corpus": "fixtures/yaml-conformance", - "_comment": "Cross-port YAML divergences ledgered as known-gap (the runner treats listed fixtures as passing). yaml-quoted-leading-zero: Java's pipeline strips the quotes on '\"007\"' so the canonical output reads the value as int 7 instead of string \"007\". TS yaml, PyYAML, YamlDotNet all preserve the quoted form; Java's desugar/canonical path silently re-coerces. Cross-port reference TS produces `@column: \"007\"`; Java produces `@column: 7`. Tracks the lib-vs-pipeline divergence; reconcile by quoting-preservation fix in Java.", - "fixtures": [ - "yaml-quoted-leading-zero" - ] + "fixtures": [] } From 11b01882c8a38fb6df2f54cad14ac6b576a4fcfc Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 21:17:31 -0500 Subject: [PATCH 4/8] feat(omdb): persist int-backed enum arrays An int-backed field.enum array stores each member as its declared integer: a native integer[] on Postgres, a JSON array of numbers in a text column on SQLite, MySQL and Derby. A member with no declared integer is refused on write and a stored integer with no member fails the read. The shared roundtrip-int-enum-array scenario now runs on Postgres, SQLite and MySQL in the Java lane, so its deferral is gone. --- .../integration/RoundtripWriter.java | 5 +- .../metaobjects/integration/Scenarios.java | 5 +- .../manager/db/codec/JdbcCodecs.java | 134 +++++++++++- .../manager/db/driver/GenericSQLDriver.java | 21 ++ .../manager/db/driver/PostgresDriver.java | 2 + .../driver/IntBackedEnumArrayRefusalTest.java | 124 ----------- .../db/driver/IntBackedEnumArrayTest.java | 192 ++++++++++++++++++ 7 files changed, 344 insertions(+), 139 deletions(-) delete mode 100644 server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayRefusalTest.java create mode 100644 server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayTest.java diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/RoundtripWriter.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/RoundtripWriter.java index 684bd22871..d526d9d2d7 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/RoundtripWriter.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/RoundtripWriter.java @@ -178,7 +178,10 @@ private static void setNative(ValueObject vo, MetaField mf, Object raw) { String name = mf.getName(); if (raw == null) { vo.setObject(name, null); return; } - if (mf instanceof StringField || mf instanceof EnumField) { + if (mf instanceof EnumField && mf.isArrayType() && raw instanceof java.util.List members) { + // An enum ARRAY: the member symbols as a list (setString would store the list's text). + vo.setObjectArray(name, members.stream().map(m -> m == null ? null : m.toString()).toList()); + } else if (mf instanceof StringField || mf instanceof EnumField) { vo.setString(name, raw.toString()); } else if (mf instanceof UriField || mf instanceof InetField) { // field.uri / field.inet are String-backed scalars (DataTypes.STRING). Author the URI / diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java index 2cfd1ba8ba..1ed666672b 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java @@ -15,10 +15,7 @@ private Scenarios() {} * blocks it. A runner aborts (skips) a listed scenario instead of failing it; every other * scenario under {@code queries/} runs, so a new fixture auto-runs or auto-fails. */ - public static final Map DEFERRED = Map.of( - "roundtrip-int-enum-array", - "OMDB persists no field.enum array of either kind: no driver maps an enum to an array column (PostgresDriver.nativeArrayElementType answers text/uuid/numeric only, and SQLite/MySQL have no primitive-array path), so the int-backed enum codec refuses the array rather than store symbols." - ); + public static final Map DEFERRED = Map.of(); public record SortSpec(String field, String dir) {} diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java index 85269935b6..42979f710d 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java @@ -80,6 +80,79 @@ public static JdbcFieldCodec defaultCodec() { return DEFAULT; } + /** + * The declared symbol→int map of an INT-BACKED {@code field.enum} (own or inherited, + * ADR-0039), or {@code null} for a string-backed enum or any other field. The drivers use it + * to decide that an enum ARRAY is a native {@code integer[]}. + */ + public static Map enumIntValueMap(MetaField f) { + return EnumField.SUBTYPE_ENUM.equals(f.getSubType()) ? EnumCodec.intValueMap(f) : null; + } + + /** + * The stored integers of an int-backed enum array's members, in order (a null member stays + * null). A member with no declared integer throws: binding the symbol would store a spelling + * the column does not hold, and inventing a number would store a row nobody wrote. + */ + public static Integer[] encodeIntEnumList(MetaField f, Object value) throws SQLException { + Map intMap = enumIntValueMap(f); + if (intMap == null) { + throw new SQLException("field.enum '" + f.getName() + "' declares no @" + EnumField.ATTR_INT_VALUE_MAP); + } + java.util.List list = (value instanceof java.util.List l) ? l : java.util.List.of(value); + Integer[] out = new Integer[list.size()]; + for (int i = 0; i < out.length; i++) { + Object e = list.get(i); + if (e == null) continue; + Integer mapped = intMap.get(e.toString()); + if (mapped == null) { + throw new SQLException("field.enum '" + f.getName() + "' cannot bind " + e + + ": it has no integer in @" + EnumField.ATTR_INT_VALUE_MAP + " (declared: " + intMap + ")"); + } + out[i] = mapped; + } + return out; + } + + /** + * The members of an int-backed enum array's stored integers, in order. A stored integer with + * no member throws, as an unmapped scalar does: the database holds a value the model does not + * describe. + */ + public static java.util.List decodeIntEnumList(MetaField f, Iterable stored) throws SQLException { + Map intMap = enumIntValueMap(f); + if (intMap == null) { + throw new SQLException("field.enum '" + f.getName() + "' declares no @" + EnumField.ATTR_INT_VALUE_MAP); + } + return decodeIntEnumList(f, intMap, stored); + } + + private static java.util.List decodeIntEnumList(MetaField f, Map intMap, Iterable stored) + throws SQLException { + java.util.List out = new java.util.ArrayList<>(); + for (Object element : stored) { + if (element == null) { + out.add(null); + continue; + } + int value = ((Number) element).intValue(); + String member = null; + for (Map.Entry e : intMap.entrySet()) { + if (e.getValue() != null && e.getValue() == value) { + member = e.getKey(); + break; + } + } + if (member == null) { + throw new SQLException("field.enum '" + f.getName() + "' read stored value " + value + + " with no member in @" + EnumField.ATTR_INT_VALUE_MAP + " (declared: " + intMap + + ") — the database holds a value the model does not describe."); + } + out.add(member); + } + return out; + } + public static JdbcFieldCodec forField(MetaField f) { return BY_TYPE.getOrDefault(f.getClass(), DEFAULT); } @@ -461,7 +534,10 @@ static final class EnumCodec implements JdbcFieldCodec { + " (declared: " + storedMap + ") — the database holds a value the model " + "does not describe."); } - refuseArray(f); + if (f.isArrayType()) { + readIntArray(o, f, intMap, rs.getString(j)); + return; + } int stored = rs.getInt(j); if (rs.wasNull()) { f.setString(o, null); @@ -512,7 +588,14 @@ static final class EnumCodec implements JdbcFieldCodec { s.setString(j, stored); return; } - refuseArray(f); + if (f.isArrayType()) { + if (v == null) { + s.setNull(j, Types.VARCHAR); + return; + } + s.setString(j, jsonIntArray(encodeIntEnumList(f, v))); + return; + } if (v == null) { s.setNull(j, Types.INTEGER); return; @@ -528,13 +611,44 @@ static final class EnumCodec implements JdbcFieldCodec { s.setString(j, v.toString()); } - /** Throws when an int-backed enum is an ARRAY: OMDB has no enum-array column to store it in. */ - private static void refuseArray(MetaField f) throws SQLException { - if (!f.isArrayType()) return; - throw new SQLException( - "field.enum '" + f.getName() + "' is an int-backed array (@" + EnumField.ATTR_INT_VALUE_MAP - + " with isArray) — OMDB persists no enum array, so it refuses rather than store " - + "the member symbols or read a member nobody stored."); + /** + * An int-backed ARRAY on an engine with no native array column (SQLite, MySQL, Derby): a + * JSON array of numbers in a text/JSON column ({@code [5,0]}, {@code []}, SQL NULL), + * the same form every other port stores. A native {@code integer[]} (Postgres) never gets + * here: the driver binds and reads it before the codec is asked. + */ + private static void readIntArray(Object o, MetaField f, Map intMap, String json) + throws SQLException { + if (json == null) { + f.setObjectArray(o, null); + return; + } + java.util.List stored = new java.util.ArrayList<>(); + try { + com.google.gson.JsonElement parsed = com.google.gson.JsonParser.parseString(json); + if (!parsed.isJsonArray()) { + throw new SQLException("field.enum '" + f.getName() + "' read stored value " + json + + ", which is not a JSON array of numbers"); + } + for (com.google.gson.JsonElement e : parsed.getAsJsonArray()) { + stored.add(e.isJsonNull() ? null : e.getAsInt()); + } + } catch (com.google.gson.JsonParseException | NumberFormatException | UnsupportedOperationException + | IllegalStateException e) { + throw new SQLException("field.enum '" + f.getName() + "' read stored value " + json + + ", which is not a JSON array of numbers", e); + } + f.setObjectArray(o, decodeIntEnumList(f, intMap, stored)); + } + + /** {@code [5,0]}: the stored form of an int-backed enum array on an engine with no array type. */ + private static String jsonIntArray(Integer[] ints) { + StringBuilder out = new StringBuilder("["); + for (int i = 0; i < ints.length; i++) { + if (i > 0) out.append(','); + out.append(ints[i] == null ? "null" : ints[i].toString()); + } + return out.append(']').toString(); } /** rc.21 — the declared member→stored-string map ({@code @stringValueMap}, resolving), or null. */ @@ -551,7 +665,7 @@ private static Map stringValueMap(MetaField f) { } /** The declared symbol→int map, or null when the enum is string-backed. */ - private static Map intValueMap(MetaField f) { + static Map intValueMap(MetaField f) { if (!f.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null; Object raw = f.getMetaAttr(EnumField.ATTR_INT_VALUE_MAP).getValue(); if (!(raw instanceof Map)) return null; diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/GenericSQLDriver.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/GenericSQLDriver.java index cfa344ad49..852f4a066d 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/GenericSQLDriver.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/GenericSQLDriver.java @@ -277,6 +277,9 @@ protected String nativeArrayElementType(MetaField f) { return null; } + /** The native element type of an int-backed {@code field.enum} array: each member is its declared integer. */ + protected static final String INT_ENUM_ARRAY_ELEMENT = "integer"; + /** * Bind a {@code List} value to a native SQL array parameter ({@code text[]} / {@code uuid[]}). * A {@code uuid[]} binds {@link java.util.UUID} elements (a String element would draw a @@ -1479,6 +1482,14 @@ protected void setStatementValue(PreparedStatement s, MetaField f, int index, Ob // from the connection so pgjdbc routes the List to the array column. String arrayElemType = nativeArrayElementType(f); if (arrayElemType != null) { + if (INT_ENUM_ARRAY_ELEMENT.equals(arrayElemType)) { + // An int-backed enum array: each member binds as its declared integer. + Integer[] ints = value == null ? null + : com.metaobjects.manager.db.codec.JdbcCodecs.encodeIntEnumList(f, value); + if (ints == null) s.setNull(index, Types.ARRAY); + else s.setArray(index, s.getConnection().createArrayOf("integer", ints)); + return; + } bindNativeArrayParameter(s, index, arrayElemType, value); return; } @@ -1754,6 +1765,16 @@ protected void parseField(Object o, MetaField f, ResultSet rs, int j) throws SQL // branch below, since a `field.uuid isArray` matches isUuidColumn on subtype too. String arrayElemType = nativeArrayElementType(f); if (arrayElemType != null) { + if (INT_ENUM_ARRAY_ELEMENT.equals(arrayElemType)) { + java.sql.Array sqlArr = rs.getArray(j); + if (sqlArr == null || rs.wasNull()) { + f.setObjectArray(o, null); + } else { + f.setObjectArray(o, com.metaobjects.manager.db.codec.JdbcCodecs.decodeIntEnumList( + f, java.util.Arrays.asList((Object[]) sqlArr.getArray()))); + } + return; + } readNativeArrayInto(o, f, arrayElemType, rs, j); return; } diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/PostgresDriver.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/PostgresDriver.java index fff406cf60..8a1f25e22b 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/PostgresDriver.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/driver/PostgresDriver.java @@ -230,6 +230,8 @@ protected String nativeArrayElementType(com.metaobjects.field.MetaField f) { if (com.metaobjects.field.UuidField.SUBTYPE_UUID.equals(f.getSubType())) return "uuid"; // field.decimal isArray is a native NUMERIC[] (no bound on the elements; the wire layer range-checks them). if (com.metaobjects.field.DecimalField.SUBTYPE_DECIMAL.equals(f.getSubType())) return "numeric"; + // An int-backed field.enum isArray is a native INTEGER[] holding each member's declared integer. + if (com.metaobjects.manager.db.codec.JdbcCodecs.enumIntValueMap(f) != null) return "integer"; if (com.metaobjects.field.StringField.SUBTYPE_STRING.equals(f.getSubType()) && !isOpenJsonbField(f)) { return "text"; diff --git a/server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayRefusalTest.java b/server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayRefusalTest.java deleted file mode 100644 index e94c8f5d96..0000000000 --- a/server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayRefusalTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.metaobjects.manager.db.driver; - -import com.metaobjects.field.MetaField; -import com.metaobjects.loader.MetaDataLoader; -import com.metaobjects.loader.MetaDataSource; -import com.metaobjects.object.MetaObject; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * An int-backed {@code field.enum} ARRAY ({@code @intValueMap} + {@code isArray}, here inherited - * from a shared abstract enum) loads, but OMDB persists no enum array of either kind: no driver - * maps an enum to a native array column ({@link PostgresDriver#nativeArrayElementType} answers - * only {@code text} / {@code uuid} / {@code numeric}), so the value reaches the SCALAR enum codec. - * - *

That codec must refuse rather than guess. Before the refusal it bound the list's - * {@code toString()} — the member SYMBOLS, {@code "[PUBLISHED, DRAFT]"} — into the column, which a - * text-affinity SQLite column accepted silently; and it read a stored {@code "[5,0]"} through - * {@code getInt}, which SQLite answers with {@code 0}: a member nobody stored. Both are the failure - * an int-backed array must never have. A real in-memory SQLite proves it, since it is the engine - * that accepts both silently.

- */ -public class IntBackedEnumArrayRefusalTest { - - private static final String META = "{ \"metadata.root\": { \"package\": \"ivm\", \"children\": [" - + " { \"field.enum\": { \"name\": \"Stage\", \"abstract\": true," - + " \"@values\": [\"DRAFT\", \"PUBLISHED\", \"ARCHIVED\"]," - + " \"@intValueMap\": { \"DRAFT\": 0, \"PUBLISHED\": 5, \"ARCHIVED\": 9 } } }," - + " { \"object.entity\": { \"name\": \"Doc\", \"children\": [" - + " { \"source.rdb\": { \"@table\": \"doc\" } }," - + " { \"field.long\": { \"name\": \"id\" } }," - + " { \"field.enum\": { \"name\": \"stage\", \"extends\": \"ivm::Stage\" } }," - + " { \"field.enum\": { \"name\": \"history\", \"extends\": \"ivm::Stage\", \"isArray\": true } }," - + " { \"identity.primary\": { \"name\": \"id\", \"@fields\": \"id\" } }" - + " ] } }" - + "] } }"; - - /** Exposes the protected bind and read hooks. */ - private static final class TestDriver extends SQLiteDriver { - void bind(PreparedStatement s, MetaField f, int i, Object v) throws SQLException { - setStatementValue(s, f, i, v); - } - void read(Object o, MetaField f, ResultSet rs, int j) throws SQLException { - parseField(o, f, rs, j); - } - } - - private static MetaField history; - private static MetaField stage; - private final TestDriver driver = new TestDriver(); - - @BeforeClass - public static void load() { - MetaDataLoader loader = MetaDataLoader.fromString( - "ivm-array-" + UUID.randomUUID().toString().substring(0, 8), META, MetaDataSource.MetaDataFormat.JSON); - MetaObject doc = loader.getMetaObjectByName("ivm::Doc"); - history = doc.getMetaField("history"); - stage = doc.getMetaField("stage"); - } - - @Test - public void writingAnArrayRefusesInsteadOfStoringTheSymbols() throws Exception { - try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { - st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); - try (PreparedStatement ps = c.prepareStatement("INSERT INTO doc (id, history) VALUES (1, ?)")) { - try { - driver.bind(ps, history, 1, List.of("PUBLISHED", "DRAFT")); - ps.executeUpdate(); - } catch (SQLException expected) { - assertTrue(expected.getMessage(), expected.getMessage().contains("history")); - } - } - try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM doc")) { - assertTrue(rs.next()); - assertEquals("no row may hold the member symbols", 0, rs.getInt(1)); - } - } - } - - @Test - public void readingAnArrayRefusesInsteadOfInventingAMember() throws Exception { - try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { - st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); - st.execute("INSERT INTO doc VALUES (1, '[5,0]')"); - try (ResultSet rs = st.executeQuery("SELECT history FROM doc")) { - assertTrue(rs.next()); - HashMap row = new HashMap<>(); - driver.read(row, history, rs, 1); - fail("reading an int-backed enum array through the scalar codec must throw; read " + row); - } catch (SQLException expected) { - assertTrue(expected.getMessage(), expected.getMessage().contains("history")); - } - } - } - - @Test - public void theScalarSiblingSharingTheMapStillStoresItsInt() throws Exception { - try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { - st.execute("CREATE TABLE doc (id INTEGER, stage INTEGER)"); - try (PreparedStatement ps = c.prepareStatement("INSERT INTO doc (id, stage) VALUES (1, ?)")) { - driver.bind(ps, stage, 1, "PUBLISHED"); - ps.executeUpdate(); - } - try (ResultSet rs = st.executeQuery("SELECT stage FROM doc")) { - assertTrue(rs.next()); - assertEquals(5, rs.getInt(1)); - } - } - } -} diff --git a/server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayTest.java b/server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayTest.java new file mode 100644 index 0000000000..ccaefe1f79 --- /dev/null +++ b/server/java/omdb/src/test/java/com/metaobjects/manager/db/driver/IntBackedEnumArrayTest.java @@ -0,0 +1,192 @@ +package com.metaobjects.manager.db.driver; + +import com.metaobjects.field.MetaField; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.loader.MetaDataSource; +import com.metaobjects.object.MetaObject; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * An int-backed {@code field.enum} ARRAY ({@code @intValueMap} + {@code isArray}, here inherited + * from a shared abstract enum) stores each member as its declared integer and reads each integer + * back as its member: a native {@code integer[]} on Postgres, a JSON array of numbers + * ({@code [5,0]}) in a text column everywhere else. A member symbol is never stored and a member + * nobody declared is never invented, on either side. A real in-memory SQLite proves the JSON-text + * form, since it is the engine that accepted the symbols silently before the array was supported. + */ +public class IntBackedEnumArrayTest { + private static final String META = "{ \"metadata.root\": { \"package\": \"ivm\", \"children\": [" + + " { \"field.enum\": { \"name\": \"Stage\", \"abstract\": true," + + " \"@values\": [\"DRAFT\", \"PUBLISHED\", \"ARCHIVED\"]," + + " \"@intValueMap\": { \"DRAFT\": 0, \"PUBLISHED\": 5, \"ARCHIVED\": 9 } } }," + + " { \"object.entity\": { \"name\": \"Doc\", \"children\": [" + + " { \"source.rdb\": { \"@table\": \"doc\" } }," + + " { \"field.long\": { \"name\": \"id\" } }," + + " { \"field.enum\": { \"name\": \"stage\", \"extends\": \"ivm::Stage\" } }," + + " { \"field.enum\": { \"name\": \"history\", \"extends\": \"ivm::Stage\", \"isArray\": true } }," + + " { \"identity.primary\": { \"name\": \"id\", \"@fields\": \"id\" } }" + + " ] } }" + + "] } }"; + + /** Exposes the protected bind and read hooks. */ + private static final class TestDriver extends SQLiteDriver { + void bind(PreparedStatement s, MetaField f, int i, Object v) throws SQLException { + setStatementValue(s, f, i, v); + } + void read(Object o, MetaField f, ResultSet rs, int j) throws SQLException { + parseField(o, f, rs, j); + } + } + + private static MetaField history; + private static MetaField stage; + private final TestDriver driver = new TestDriver(); + + @BeforeClass + public static void load() { + MetaDataLoader loader = MetaDataLoader.fromString( + "ivm-array-" + UUID.randomUUID().toString().substring(0, 8), META, MetaDataSource.MetaDataFormat.JSON); + MetaObject doc = loader.getMetaObjectByName("ivm::Doc"); + history = doc.getMetaField("history"); + stage = doc.getMetaField("stage"); + } + + private static String stored(Connection c, int id) throws SQLException { + try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery("SELECT history FROM doc WHERE id = " + id)) { + assertTrue(rs.next()); + return rs.getString(1); + } + } + + private void insert(Connection c, int id, Object value) throws SQLException { + try (PreparedStatement ps = c.prepareStatement("INSERT INTO doc (id, history) VALUES (" + id + ", ?)")) { + driver.bind(ps, history, 1, value); + ps.executeUpdate(); + } + } + + @SuppressWarnings("unchecked") + private Object read(Connection c, int id) throws SQLException { + try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery("SELECT history FROM doc WHERE id = " + id)) { + assertTrue(rs.next()); + HashMap row = new HashMap<>(); + driver.read(row, history, rs, 1); + return history.getObjectArray(row); + } + } + + @Test + public void anArrayStoresEachMembersDeclaredIntegerNotTheSymbols() throws Exception { + try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { + st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); + insert(c, 1, List.of("PUBLISHED", "DRAFT")); + insert(c, 2, List.of()); + insert(c, 3, null); + assertEquals("[5,0]", stored(c, 1)); + assertEquals("[]", stored(c, 2)); + assertEquals(null, stored(c, 3)); + } + } + + @Test + public void storedIntegersReadBackAsMembersInOrderAndNullStaysNull() throws Exception { + try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { + st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); + st.execute("INSERT INTO doc VALUES (1, '[5,0]'), (2, '[]'), (3, NULL), (4, '[9]')"); + assertEquals(List.of("PUBLISHED", "DRAFT"), read(c, 1)); + assertEquals(List.of(), read(c, 2)); + assertEquals(null, read(c, 3)); + assertEquals(List.of("ARCHIVED"), read(c, 4)); + } + } + + @Test + public void aStoredIntegerWithNoMemberFailsTheRead() throws Exception { + try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { + st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); + st.execute("INSERT INTO doc VALUES (1, '[5,42]')"); + try { + read(c, 1); + fail("an unmapped stored element must throw, as an unmapped scalar does"); + } catch (SQLException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("history")); + assertTrue(expected.getMessage(), expected.getMessage().contains("42")); + } + } + } + + @Test + public void storedTextThatIsNotAnArrayOfNumbersFailsTheRead() throws Exception { + try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { + st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); + st.execute("INSERT INTO doc VALUES (1, 'PUBLISHED')"); + try { + read(c, 1); + fail("text that is not a JSON array of numbers must throw"); + } catch (SQLException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("history")); + } + } + } + + @Test + public void aMemberWithNoDeclaredIntegerIsRefusedAndNothingIsStored() throws Exception { + try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { + st.execute("CREATE TABLE doc (id INTEGER, history TEXT)"); + try { + insert(c, 1, List.of("PUBLISHED", "NOT_A_MEMBER")); + fail("an unmapped member must not be bound"); + } catch (SQLException expected) { + assertTrue(expected.getMessage(), expected.getMessage().contains("NOT_A_MEMBER")); + } + try (ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM doc")) { + assertTrue(rs.next()); + assertEquals("no row may be written", 0, rs.getInt(1)); + } + } + } + + /** Exposes the protected element-type hook of the Postgres driver. */ + private static final class PgDriver extends PostgresDriver { + String elementType(MetaField f) { + return nativeArrayElementType(f); + } + } + + @Test + public void postgresMapsTheArrayToANativeIntegerArrayAndTheScalarToNone() { + PgDriver pg = new PgDriver(); + assertEquals("integer", pg.elementType(history)); + assertEquals(null, pg.elementType(stage)); + } + + @Test + public void theScalarSiblingSharingTheMapStillStoresItsInt() throws Exception { + try (Connection c = DriverManager.getConnection("jdbc:sqlite::memory:"); Statement st = c.createStatement()) { + st.execute("CREATE TABLE doc (id INTEGER, stage INTEGER)"); + try (PreparedStatement ps = c.prepareStatement("INSERT INTO doc (id, stage) VALUES (1, ?)")) { + driver.bind(ps, stage, 1, "PUBLISHED"); + ps.executeUpdate(); + } + try (ResultSet rs = st.executeQuery("SELECT stage FROM doc")) { + assertTrue(rs.next()); + assertEquals(5, rs.getInt(1)); + } + } + } +} From df4d58de315e3b3355ccf639b9d8d16f2186677e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 21:43:24 -0500 Subject: [PATCH 5/8] feat(codegen-kotlin): emit an integer array column for int-backed enum arrays An isArray field.enum with an @intValueMap now gets portableIntEnumArray: a native INTEGER[] on Postgres and a JSON array of numbers on SQLite and MySQL, with the symbol-to-integer mapping inlined as when expressions. The column type goes in its own MetaIntEnumArrayColumnType.kt support file, written only into a package that has such a column. The roundtrip-int-enum-array scenario runs in the Kotlin lane, the compile gates no longer leave out the IntEnumArray tier, and the docs and known-gaps entry say what is left (string-backed enum arrays). --- .claude/rules/cross-language-porting.md | 2 +- CHANGELOG.md | 10 +- docs/features/field-types.md | 3 +- docs/ports/java.md | 16 +-- docs/ports/kotlin.md | 25 +++-- .../Exposed1xControllerCompileTest.kt | 11 -- .../generator/kotlin/KNOWN_GAPS.md | 19 ++-- .../kotlin/KotlinExposedTableGenerator.kt | 100 ++++++++++++++++++ .../generator/kotlin/KotlinTypeMapper.kt | 16 +++ .../KotlinExposedTableIntBackedEnumTest.kt | 56 ++++++++++ .../enum-int-backed-array/meta.shop.json | 27 +++++ .../integration/kotlin/QueryScenarioRunner.kt | 5 + .../integration/kotlin/Scenarios.kt | 5 +- .../FitnessCorpusControllerCompileTest.kt | 11 -- .../codegen/GeneratorRequiresCompileTest.kt | 12 --- .../kotlin/tables/IntBackedEnumColumnType.kt | 62 +++++++++++ .../kotlin/tables/IntEnumArrayTable.kt | 16 +++ 17 files changed, 325 insertions(+), 71 deletions(-) create mode 100644 server/java/codegen-kotlin/src/test/resources/models/enum-int-backed-array/meta.shop.json create mode 100644 server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntEnumArrayTable.kt diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 4966f27c3b..685d923a42 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -31,7 +31,7 @@ Preserve the following contracts exactly across all language ports: - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) - Storage attrs: `@storage` on `field.object` (with `@objectRef`) — values `flattened` / `jsonb` / `subdocument`. Unifies "owned types" (flattened storage) and "structured JSONB" (jsonb storage). Defaults to single-jsonb-column when absent (back-compat). -- Enum: `field.enum` is a first-class field subtype (peer of `currency`), string-backed. Required `@values` string-array attr (member symbols). Members must be a non-empty set, each matching `^[A-Za-z_][A-Za-z0-9_]*$`, no duplicates — every port's loader enforces this (own-only) emitting `ERR_BAD_ATTR_VALUE` (missing `@values` → `ERR_MISSING_REQUIRED_ATTR`). Reuse via abstract `field.enum` + `extends`. Codegen: TS union + `z.enum`, C# `enum` + EF `HasConversion()`, DB `varchar` + `CHECK`. **Int-backed storage shipped** (`@intValueMap`, a `{memberSymbol: int}` map, switches the column to `integer` + int `CHECK` while the wire format, the generated type and every runtime value stay the member SYMBOL; a MAP rather than a positional array so reordering `@values` cannot silently re-map every member; an int-backed enum array loads in every port and stores each element as its declared integer — TypeScript and C# persist it on every engine, Python on Postgres only, Java's OMDB refuses it at the codec, and Kotlin's Exposed generator emits no enum array column yet; an unmapped stored integer THROWS in all five ports). Display labels and native PG enum remain deferred (see `docs/superpowers/specs/2026-05-23-enum-datatype-design.md`). +- Enum: `field.enum` is a first-class field subtype (peer of `currency`), string-backed. Required `@values` string-array attr (member symbols). Members must be a non-empty set, each matching `^[A-Za-z_][A-Za-z0-9_]*$`, no duplicates — every port's loader enforces this (own-only) emitting `ERR_BAD_ATTR_VALUE` (missing `@values` → `ERR_MISSING_REQUIRED_ATTR`). Reuse via abstract `field.enum` + `extends`. Codegen: TS union + `z.enum`, C# `enum` + EF `HasConversion()`, DB `varchar` + `CHECK`. **Int-backed storage shipped** (`@intValueMap`, a `{memberSymbol: int}` map, switches the column to `integer` + int `CHECK` while the wire format, the generated type and every runtime value stay the member SYMBOL; a MAP rather than a positional array so reordering `@values` cannot silently re-map every member; an int-backed enum array loads in every port and stores each element as its declared integer — TypeScript, C#, Java (OMDB) and Kotlin (Exposed) persist it on every engine, Python on Postgres only; an unmapped stored integer THROWS in all five ports). Display labels and native PG enum remain deferred (see `docs/superpowers/specs/2026-05-23-enum-datatype-design.md`). - Documentation common attrs (any node): `description`, `title`, `notes`, `deprecated`, `replacedBy`, `seeAlso`, `aliases`. Registered via the cross-language `commonAttrs` registry hook (`registerCommonAttrs` / `RegisterCommonAttrs` / `register_common_attrs` / Java `MetaDataRegistry.registerCommonAttribute` — wired in all four ports). `notes` is the internal-only rationale slot — never emitted to user-facing doc-gen (JSDoc / XML-doc / Postgres `COMMENT ON` / Mermaid prose). **The `description` / `notes` split is by CONTENT KIND, not audience** — an audience split invites writing the same content twice at two levels of politeness. `description` states what the element IS and COVERS (scope and boundary, derivable from the model); `notes` states what you had to look OUTSIDE the model to learn (evidence, citations, what breaks if it changes). Mechanical test: a sentence belongs in `notes` exactly when it would have to change because the IMPLEMENTATION changed while the model did not. `title` is a noun phrase, `summary` a one-line sentence. TS doc-gen ships all three tiers; C# ships XML-doc + COMMENT ON. See `docs/superpowers/specs/2026-05-24-documentation-provider-design.md`. **Wire format:** diff --git a/CHANGELOG.md b/CHANGELOG.md index 144927c3c9..d34ba6f787 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -628,10 +628,12 @@ Each item below is described in full under Security, Added, Changed or Fixed; th nullable. - Python: ObjectManager maps elements on write, read and filter operands on Postgres. Its SQLite and MySQL dialects store no primitive array, so the new scenario is deferred there. - - Java: OMDB stores no enum array on any engine, so its codec refuses an int-backed one on - write and read instead of writing symbols. Kotlin's Exposed table generator emits a scalar - column for an enum array, so generated code for an int-backed enum array does not compile - yet (see `KNOWN_GAPS.md`). Both defer the new scenario. + - Java: OMDB stores an int-backed enum array as a native `integer[]` on Postgres and a JSON array + of numbers on SQLite, MySQL and Derby; a member with no declared integer is refused on write, + and a stored integer with no member fails the read. Kotlin: the Exposed table generator emits an + integer array column for it (`portableIntEnumArray`, in a `MetaIntEnumArrayColumnType.kt` support + file written only into a package that has such a column), where it used to emit a scalar column + that did not compile. The new scenario runs in both. Gated by the positive conformance fixtures `enum-int-backed-array` and `enum-int-backed-array-inherited`, and the persistence scenario `roundtrip-int-enum-array`. diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 33faff0d95..a1c30f2d5e 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -249,7 +249,8 @@ Two rules follow from int-backing being a **persistence-layer codec**: back as its member. A null array stays null and an empty one stays empty. The array column has no `CHECK`, the same as a string-backed enum array. Where a port's runtime stores no primitive array on an engine, it refuses an int-backed one there rather than writing - symbols: see that port's page under [docs/ports/](../ports/). + symbols: see that port's page under [docs/ports/](../ports/). (Python on SQLite and MySQL is + the one place that still does.) - **A stored integer that maps to no member throws on read**, in every port. The row holds data the model says is impossible (a hand-written `INSERT`, or a member removed without a migration); surfacing the raw integer would hand you a "member" that is not one — and is diff --git a/docs/ports/java.md b/docs/ports/java.md index 452f8f8c0d..f6306b15bc 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -1044,13 +1044,15 @@ the runtime classpath, and no stored-procedure callable generator exists (FR-015 TypeScript, C# and Kotlin only). OMDB is data access only; schema migrations are owned by the Node `meta` CLI. -OMDB persists no `field.enum` array, string-backed or int-backed. On Postgres a native array column -is mapped only for `field.string`, `field.uuid` and `field.decimal` (`PostgresDriver.nativeArrayElementType`), -and the other drivers have no primitive-array path. An int-backed enum array (`@intValueMap` with -`isArray: true`, own or inherited) loads, but the enum codec refuses it on write and on read with an -`SQLException` naming the field. Without that refusal the scalar codec would write the member -symbols, and on SQLite it would read a stored `[5,0]` as `DRAFT`. The `roundtrip-int-enum-array` -persistence scenario is deferred in the Java runners for this reason. The generated Spring enum for +OMDB persists an int-backed `field.enum` array (`@intValueMap` with `isArray: true`, own or +inherited) as each member's declared integer: a native `integer[]` on Postgres +(`PostgresDriver.nativeArrayElementType`), and on SQLite, MySQL and Derby a JSON array of numbers +(`[5,0]`) in a text column, read back as the members in order. A member with no declared integer is +refused on write with an `SQLException` naming the field, and a stored integer with no member fails +the read the way an unmapped scalar does; a null array stays null and an empty one stays empty. The +`roundtrip-int-enum-array` persistence scenario runs in the Java runners. A string-backed enum array +is not covered: a native array column is mapped only for `field.string`, `field.uuid`, +`field.decimal` and the int-backed enum. The generated Spring enum for an int-backed enum carries `dbValue()` and `fromDbValue(int)`, and the payload types an array field as `List`, so a repository you write maps each element. diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index c8ea1b98c0..2b60673517 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -478,8 +478,8 @@ reactor's 2.0.21; its round-trip test additionally needs docker. Run via selection compiles every entity's generated `Controller.kt` — TPH, M:N, view projections, and every `emitPerFieldDispatchArm` operator arm across every scalar subtype — against real Spring 6.2 (`spring-webmvc`) + jakarta.servlet + Jackson on the - module's test classpath (real dependencies, not stubs), with one exclusion: - `IntEnumArrayController.kt` (see [Enum arrays](#enum-arrays) below). The + module's test classpath (real dependencies, not stubs), over every + entity, the int-backed enum array's included (see [Enum arrays](#enum-arrays) below). The per-field dispatch gate is derived from the SAME single source of truth the generated `FilterAllowlist` reads (`com.metaobjects.query.FilterOps`), so the controller can never emit an operator the allowlist itself would refuse to admit — this is also @@ -948,14 +948,19 @@ the contract is universal. ### Enum arrays A `field.enum` with `isArray: true` loads, string-backed or int-backed (`@intValueMap`, own or -inherited from a shared abstract enum). The data class types it `List`, but the Exposed table -generator has no array column for an enum of either kind: `enumColumnSpec` in -`KotlinExposedTableGenerator` emits the scalar `enumerationByName(...)` or -`customEnumeration(..., "INTEGER", ...)`, so the generated controller for such an entity does not -compile. It never stores member symbols in an integer column, because the code that would do so -does not type-check. Persist an enum array through your own column until the generator emits one. -The `roundtrip-int-enum-array` persistence scenario is deferred in this port's runners for this -reason. +inherited from a shared abstract enum), and the data class types it `List`. + +An **int-backed** enum array gets one array column over the declared integers, +`portableIntEnumArray(name, { toInt }, { fromInt })`: a native `INTEGER[]` on Postgres and a +JSON array of numbers (`[5,0]`) on SQLite and MySQL, the same stored form as every other port. +The two lambdas are the generated symbol-to-integer `when` expressions, so a member with no +integer is a compile error, and a stored integer with no member throws on read. The column type is +emitted into `MetaIntEnumArrayColumnType.kt` beside the tables, only in a package that has such a +column. The `roundtrip-int-enum-array` persistence scenario runs in this port. + +A **string-backed** enum array still has no Exposed array column: `enumColumnSpec` emits the scalar +`enumerationByName(...)` for it, so the generated controller for such an entity does not compile. +Persist it through your own column until the generator emits one. ## Drift detection (Tier-2 integration) diff --git a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt index 3229e37335..7b8c8552da 100644 --- a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt +++ b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt @@ -124,14 +124,8 @@ class Exposed1xControllerCompileTest { // See the class doc above: both AllTypesController.kt (non-Comparable field.inet // ordering ops) and AssetController.kt (the @dbColumnType=uuid escape hatch's // String/UUID mismatch) are now fixed and compile. - // `IntEnumArrayController.kt` is left out: the Exposed table generator persists no field.enum - // ARRAY of either kind — KotlinExposedTableGenerator.enumColumnSpec emits a SCALAR - // enumerationByName/customEnumeration column for an isArray enum, so the controller's - // List binding does not type-check against it. The entity and table still compile - // (CodegenCompileConformanceTest). Drop this exclusion when enum arrays get an array column. val emittedPaths: List = Files.walk(outDir) .filter { it.isRegularFile() && it.toString().endsWith(".kt") } - .filter { it.fileName.toString() != ENUM_ARRAY_CONTROLLER } .toList() assertTrue(emittedPaths.any { it.fileName.toString().endsWith("Controller.kt") }, "expected at least one Controller.kt; saw ${emittedPaths.map { it.fileName }}") @@ -151,9 +145,4 @@ class Exposed1xControllerCompileTest { outDir.toFile().deleteRecursively() } } - - private companion object { - /** See the exclusion note in the test body. */ - const val ENUM_ARRAY_CONTROLLER = "IntEnumArrayController.kt" - } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md index 6f44fd03d5..830e038dd5 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KNOWN_GAPS.md @@ -229,16 +229,15 @@ mirror deliberately stays `String` / `List`; its `toStrict()` bridges `S `valueOf`. Kept as a resolved entry (rather than deleted) because external notes referenced this section by title. -## `field.enum` arrays have no Exposed array column - -An `isArray` `field.enum`, string-backed or int-backed (`@intValueMap`), is typed `List` on the -data class, but `KotlinExposedTableGenerator.enumColumnSpec` emits a SCALAR column for it -(`enumerationByName` / `customEnumeration(..., "INTEGER", ...)`), so the generated controller for -the entity does not compile. Nothing silently stores symbols: the mismatch fails the build. The fix -is an array column whose element codec is the enum's: `array(col, )` on -Postgres, and a JSON text array on SQLite/MySQL as `MetaDecimalArrayColumnType` does for decimals. -Until then the compile gates leave out the fitness corpus' `IntEnumArrayController.kt` (and -`GeneratorRequiresCompileTest` its `IntEnumArrayRepository*.kt`, which bind the same column). +## String-backed `field.enum` arrays have no Exposed array column + +An `isArray` `field.enum` that is string-backed is typed `List` on the data class, but +`KotlinExposedTableGenerator.enumColumnSpec` emits a SCALAR column for it (`enumerationByName` / +`customEnumeration`), so the generated controller for the entity does not compile. Nothing silently +stores symbols in the wrong column: the mismatch fails the build. The fix is the same shape as the +int-backed one, which has its own array column (`portableIntEnumArray`, in +`MetaIntEnumArrayColumnType.kt`): an array column whose element codec is the enum's. The compile +gates carry no string-backed enum array, so none of them excludes anything. ## Composite-FK relationships not emitted diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 4763bf2444..031a0e0dee 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -176,6 +176,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` builders) plus the // package's `MetaDurationWire.kt`, emitted in pass 3f. val packagesNeedingDurationHelper = sortedSetOf() + val packagesNeedingIntEnumArrayHelper = sortedSetOf() // Pass 2: emit one Table per entity using its own metadata + the // inbound FKs accumulated in Pass 1. @@ -215,6 +216,9 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` column types ([durationSupportBlock]) and, beside it, the @@ -1966,6 +1988,75 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase))" + } else { + " @Suppress(\"UNCHECKED_CAST\")\n" + + " stmt.setArray(index, \"integer\", value as Array)" + } + return """ + |private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) + | + |private fun isMySql(): Boolean = currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } + | + |/** + | * GENERATED — do not hand-edit. An int-backed `isArray` `field.enum` column: each member is stored as + | * its declared integer, in a native `INTEGER[]` on Postgres and elsewhere (no array type) a JSON text + | * array of numbers. [toInt] and [fromInt] are the enum's symbol↔integer mapping, generated as `when` + | * expressions; an integer with no member fails the read rather than inventing one. + | */ + |internal class MetaIntEnumArrayColumnType( + | private val toInt: (E) -> Int, + | private val fromInt: (Int) -> E, + |) : ColumnType>() { + | private fun json(value: List): String = value.joinToString(",", "[", "]") { toInt(it).toString() } + | override fun sqlType(): String = if (isPostgres()) "INTEGER[]" else if (isMySql()) "JSON" else "TEXT" + | override fun valueFromDB(value: Any): List = when (value) { + | is java.sql.Array -> (value.array as Array<*>).map { fromInt((it as Number).toInt()) } + | is Array<*> -> value.map { fromInt((it as Number).toInt()) } + | is List<*> -> value.map { fromInt((it as Number).toInt()) } + | else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { fromInt(it.intValue()) } + | } + | override fun notNullValueToDB(value: List): Any = + | if (isPostgres()) value.map { toInt(it) }.toTypedArray() else json(value) + | override fun nonNullValueToString(value: List): String = + | if (isPostgres()) value.joinToString(",", "ARRAY[", "]::integer[]") { toInt(it).toString() } else "'" + json(value) + "'" + | override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { + | if (value is Array<*>) { + |$intArrayBind + | } else { + | super.setParameter(stmt, index, value) + | } + | } + |} + | + |/** Column builder for an int-backed `isArray` `field.enum`: a `Column>`. */ + |internal fun Table.portableIntEnumArray(name: String, toInt: (E) -> Int, fromInt: (Int) -> E): Column> = + | registerColumn(name, MetaIntEnumArrayColumnType(toInt, fromInt)) + |""".trimMargin() + } + /** File name (sans `.kt`) of the per-package support file for `field.uuid` and `field.decimal` columns. */ const val PORTABLE_SUPPORT_FILE_NAME = "MetaPortableColumnTypes" @@ -2761,6 +2852,15 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase ...`). val fromDb = intMap.entries.joinToString("; ") { (sym, i) -> "$i -> $simple.$sym" } val toDb = intMap.entries.joinToString("; ") { (sym, i) -> "$simple.$sym -> $i" } + if (KotlinTypeMapper.isIntBackedEnumArray(field)) { + // An int-backed enum ARRAY: one integer[] column (a JSON text array of numbers where + // there is no array type) whose element codec is the same mapping as the scalar's. + // The scalar form would not type-check against the `List` property, and it must + // never store the member symbols. + return "${KotlinTypeMapper.EXPOSED_PORTABLE_INT_ENUM_ARRAY_FN}<$simple>($colExpr, " + + "{ e -> when (e) { $toDb } }, " + + "{ i -> when (i) { $fromDb; else -> error(\"unmapped stored value \$i for $simple\") } })" + } // An int with no member is corrupt data the model does not describe: fail loudly // rather than substituting a member. The write side needs no `else` — it is // exhaustive over the enum by construction, since @intValueMap's keys are diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt index 321d11ef05..5441c7712a 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt @@ -223,6 +223,14 @@ object KotlinTypeMapper { */ const val EXPOSED_PORTABLE_DECIMAL_ARRAY_FN = "portableDecimalArray" + /** + * Builder extension for an int-backed `isArray` `field.enum` column: a `Column>` holding each + * member's declared integer, as a native `INTEGER[]` on Postgres and a JSON text array of numbers on + * MySQL and SQLite. Its own support file, emitted only for a package with such a column; the two `when` lambdas it takes + * are the generated symbol↔int mapping. + */ + const val EXPOSED_PORTABLE_INT_ENUM_ARRAY_FN = "portableIntEnumArray" + /** * Compute the generated Kotlin enum-class name for an [EnumField] hung off [entity]. * @@ -737,6 +745,14 @@ object KotlinTypeMapper { fun usesPortableHelper(field: MetaField<*>): Boolean = field is DecimalField || (field is UuidField && !isArrayResolved(field)) + /** + * True for an `isArray` `field.enum` that declares `@intValueMap` (own or inherited, ADR-0039): + * its column holds each member's declared integer, so it needs the package's + * `MetaIntEnumArrayColumnType.kt` support file. A string-backed enum array is not this. + */ + fun isIntBackedEnumArray(field: MetaField<*>): Boolean = + field is EnumField && isArrayResolved(field) && field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP) + fun usesUuidStringHelper(field: MetaField<*>): Boolean = field is StringField && !isArrayResolved(field) && dbColumnType(field) == DB_COLUMN_TYPE_UUID diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableIntBackedEnumTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableIntBackedEnumTest.kt index 23132044ca..f66bb9284c 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableIntBackedEnumTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableIntBackedEnumTest.kt @@ -93,4 +93,60 @@ class KotlinExposedTableIntBackedEnumTest { outDir.toFile().deleteRecursively() } } + + /** + * An int-backed enum ARRAY (the map inherited from a shared abstract enum, the shape adopters + * write) is one array column over the declared integers, never the scalar `customEnumeration`: + * that would not type-check against the `List` property, and must never store member symbols. + * The column type lives in its own support file, emitted only because such a column exists. + */ + @Test fun `int-backed enum array emits the integer array column and its support file and compiles`() { + val outDir = Files.createTempDirectory("ktbl-int-enum-array-") + try { + val loader = loadDirectory("enum-int-backed-array", models.resolve("enum-int-backed-array")) + for (gen in listOf(KotlinEntityGenerator(), KotlinExposedTableGenerator())) { + gen.setArgs(mapOf("outputDir" to outDir.toString())) + gen.execute(loader) + } + + val src = outDir.resolve("acme/shop/DocTable.kt").readText() + assertTrue("portableIntEnumArray(\"history\"" in src, + "history must be the integer array column; saw:\n$src") + assertTrue("Stage.DRAFT -> 0" in src && "Stage.PUBLISHED -> 5" in src && "Stage.ARCHIVED -> 9" in src, + "the write lambda must map every member to its declared int; saw:\n$src") + assertTrue("0 -> Stage.DRAFT" in src && "5 -> Stage.PUBLISHED" in src && "9 -> Stage.ARCHIVED" in src, + "the read lambda must map every declared int to its member; saw:\n$src") + assertTrue("unmapped stored value" in src, "an int with no member must fail the read; saw:\n$src") + assertTrue("customEnumeration(\"history\"" !in src, + "an array must not take the scalar column; saw:\n$src") + // The scalar sibling sharing the map keeps the scalar form. + assertTrue("customEnumeration(\"stage\", \"INTEGER\"" in src, "scalar stage unchanged; saw:\n$src") + + val support = outDir.resolve("acme/shop/MetaIntEnumArrayColumnType.kt") + assertTrue(Files.exists(support), "expected the support file; files=${Files.walk(outDir).toList()}") + val supportSrc = support.readText() + assertTrue("INTEGER[]" in supportSrc && "\"integer\"" in supportSrc, + "the support file must bind a native integer[] on Postgres; saw:\n$supportSrc") + + val result = compile(outDir) + assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode, result.messages) + } finally { + outDir.toFile().deleteRecursively() + } + } + + @Test fun `a package with no int-backed enum array gets no integer array support file`() { + val outDir = Files.createTempDirectory("ktbl-int-enum-noarray-") + try { + val loader = loadDirectory("enum-int-backed", models.resolve("enum-int-backed")) + for (gen in listOf(KotlinEntityGenerator(), KotlinExposedTableGenerator())) { + gen.setArgs(mapOf("outputDir" to outDir.toString())) + gen.execute(loader) + } + assertTrue(!Files.exists(outDir.resolve("acme/shop/MetaIntEnumArrayColumnType.kt")), + "a scalar-only int-backed enum must not emit the array support file") + } finally { + outDir.toFile().deleteRecursively() + } + } } diff --git a/server/java/codegen-kotlin/src/test/resources/models/enum-int-backed-array/meta.shop.json b/server/java/codegen-kotlin/src/test/resources/models/enum-int-backed-array/meta.shop.json new file mode 100644 index 0000000000..42b1ba973d --- /dev/null +++ b/server/java/codegen-kotlin/src/test/resources/models/enum-int-backed-array/meta.shop.json @@ -0,0 +1,27 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "field.enum": { + "name": "Stage", + "abstract": true, + "@values": ["DRAFT", "PUBLISHED", "ARCHIVED"], + "@intValueMap": { "DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9 } + } + }, + { + "object.entity": { + "name": "Doc", + "children": [ + { "source.rdb": { "name": "src", "@table": "docs", "@kind": "table" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "stage", "extends": "Stage" } }, + { "field.enum": { "name": "history", "extends": "Stage", "isArray": true } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] + } + } + ] + } +} diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt index 9e0bb0809d..edde997d78 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt @@ -42,7 +42,9 @@ import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.statements.InsertStatement import org.jetbrains.exposed.sql.transactions.transaction import com.metaobjects.integration.kotlin.tables.AllTypesTable +import com.metaobjects.integration.kotlin.tables.IntBackedEnumArrayColumnType import com.metaobjects.integration.kotlin.tables.IntBackedEnumColumnType +import com.metaobjects.integration.kotlin.tables.IntEnumArrayTable import java.math.BigDecimal import java.net.URI import java.sql.DriverManager @@ -487,6 +489,8 @@ object QueryScenarioRunner { // Int-backed field.enum: bind the member SYMBOL and let the column's codec encode it to // the stored int (see the same guard in `coerce`). if (col.columnType is IntBackedEnumColumnType) return raw.toString() + // Int-backed field.enum ARRAY: the member symbols as a list; the column's codec stores the ints. + if (col.columnType is IntBackedEnumArrayColumnType) return (raw as List<*>).map { it.toString() } // field.duration: parse the ISO-8601 authoring literal (checked BEFORE the sqlType // dispatch, whose `int` substring branch would match "interval"). if (col.columnType is MetaDurationColumnType) return com.metaobjects.field.DurationWire.parse(raw.toString()) @@ -546,6 +550,7 @@ object QueryScenarioRunner { "Session" -> SessionTable "Asset" -> AssetTable "AllTypes" -> AllTypesTable + "IntEnumArray" -> IntEnumArrayTable // ADR-0019 Amendment 1: the decimal subject table. "Entry" -> EntryTable // Two same-named tables in two schemas (`@schema`). diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt index 12b3970db6..61e2339c32 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt @@ -12,10 +12,7 @@ object Scenarios { * blocks it. Every other scenario under `queries/` runs, so a new fixture auto-runs or * auto-fails, forcing a deliberate entry here. */ - val DEFERRED: Map = mapOf( - "roundtrip-int-enum-array" to - "Exposed codegen persists no field.enum array of either kind: KotlinExposedTableGenerator.enumColumnSpec emits a SCALAR enumerationByName/customEnumeration column for an isArray enum, so the generated List property does not type-check against it; the hand-written reference tables mirror the generator.", - ) + val DEFERRED: Map = emptyMap() data class SortSpec(val field: String, val dir: String) diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/FitnessCorpusControllerCompileTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/FitnessCorpusControllerCompileTest.kt index 1b803bf5c8..d59854f27e 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/FitnessCorpusControllerCompileTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/FitnessCorpusControllerCompileTest.kt @@ -79,14 +79,8 @@ class FitnessCorpusControllerCompileTest { gen.execute(loader) } - // `IntEnumArrayController.kt` is left out: the Exposed table generator persists no field.enum - // ARRAY of either kind — KotlinExposedTableGenerator.enumColumnSpec emits a SCALAR - // enumerationByName/customEnumeration column for an isArray enum, so the controller's - // List binding does not type-check against it. The entity and table still compile - // (CodegenCompileConformanceTest). Drop this exclusion when enum arrays get an array column. val emittedPaths = Files.walk(outDir) .filter { it.isRegularFile() && it.toString().endsWith(".kt") } - .filter { it.fileName.toString() != ENUM_ARRAY_CONTROLLER } .toList() assertTrue(emittedPaths.any { it.fileName.toString().endsWith("Controller.kt") }, "expected at least one Controller.kt; saw ${emittedPaths.map { it.fileName }}") @@ -109,9 +103,4 @@ class FitnessCorpusControllerCompileTest { outDir.toFile().deleteRecursively() } } - - private companion object { - /** See the exclusion note in the test body. */ - const val ENUM_ARRAY_CONTROLLER = "IntEnumArrayController.kt" - } } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/GeneratorRequiresCompileTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/GeneratorRequiresCompileTest.kt index 5f2821dbeb..fd3f3d6c1e 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/GeneratorRequiresCompileTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/codegen/GeneratorRequiresCompileTest.kt @@ -43,13 +43,8 @@ class GeneratorRequiresCompileTest { } private fun compileErrors(root: Path): String { - // The IntEnumArray controller and repository are left out, as the controller is in - // FitnessCorpusControllerCompileTest: the Exposed table generator emits a SCALAR column for - // a field.enum array, so their List binding does not type-check against it (KNOWN_GAPS.md, "field.enum arrays have - // no Exposed array column"). Drop this exclusion when enum arrays get an array column. val sources = Files.walk(root).use { s -> s.filter { it.isRegularFile() && it.toString().endsWith(".kt") } - .filter { it.fileName.toString() !in ENUM_ARRAY_TIER } .toList() }.map { SourceFile.kotlin(root.relativize(it).toString().replace('/', '_'), it.readText()) } assertTrue(sources.isNotEmpty(), "nothing generated under $root") @@ -134,11 +129,4 @@ class GeneratorRequiresCompileTest { build.toFile().deleteRecursively() } } - - private companion object { - /** See the exclusion note in [compileErrors]. */ - val ENUM_ARRAY_TIER = setOf( - "IntEnumArrayController.kt", "IntEnumArrayRepository.kt", "IntEnumArrayRepositoryBase.kt", - ) - } } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntBackedEnumColumnType.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntBackedEnumColumnType.kt index 6801af4f66..9ba27901d0 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntBackedEnumColumnType.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntBackedEnumColumnType.kt @@ -3,6 +3,8 @@ package com.metaobjects.integration.kotlin.tables import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.ColumnType import org.jetbrains.exposed.sql.Table +import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi +import org.jetbrains.exposed.sql.vendors.currentDialect /** * Hand-written reference Exposed column type for an INT-BACKED `field.enum` (`@intValueMap`) — @@ -65,3 +67,63 @@ internal fun Table.intBackedEnum(name: String, intByMember: Map): C * must carry the fixture's map exactly (`fixtures/persistence-conformance/canonical/meta.fitness.json`). */ internal val INT_ENUM_MEMBERS: Map = mapOf("DRAFT" to 0, "PUBLISHED" to 5, "ARCHIVED" to 9) + +/** + * Hand-written reference column type for an INT-BACKED `field.enum` ARRAY: the test-harness analogue + * of the `portableIntEnumArray(...)` column [com.metaobjects.generator.kotlin.KotlinExposedTableGenerator] + * emits. Each element is stored as its declared integer: a native `INTEGER[]` on Postgres, and on + * SQLite and MySQL (no array type) a JSON array of numbers (`[5,0]`), never the member symbols. + * Like [IntBackedEnumColumnType] it carries the member SYMBOL in and out (`Column>`), + * and an integer with no member throws on the read. + */ +internal class IntBackedEnumArrayColumnType( + private val intByMember: Map, +) : ColumnType>() { + + private val memberByInt: Map = + intByMember.entries.associate { (member, stored) -> stored to member } + + private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) + private fun isMySql(): Boolean = + currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } + + private fun member(stored: Int): String = memberByInt[stored] + ?: error( + "field.enum read stored value $stored with no member in @intValueMap " + + "(declared: $intByMember) — the database holds a value the model does not describe." + ) + + private fun stored(member: String): Int = intByMember[member] + ?: error("field.enum has no @intValueMap entry for member '$member' (declared: $intByMember).") + + private fun json(value: List): String = value.joinToString(",", "[", "]") { stored(it).toString() } + + override fun sqlType(): String = if (isPostgres()) "INTEGER[]" else if (isMySql()) "JSON" else "TEXT" + + override fun valueFromDB(value: Any): List = when (value) { + is java.sql.Array -> (value.array as Array<*>).map { member((it as Number).toInt()) } + is Array<*> -> value.map { member((it as Number).toInt()) } + is List<*> -> value.map { member((it as Number).toInt()) } + else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { member(it.intValue()) } + } + + override fun notNullValueToDB(value: List): Any = + if (isPostgres()) value.map { stored(it) }.toTypedArray() else json(value) + + override fun nonNullValueToString(value: List): String = + if (isPostgres()) value.joinToString(",", "ARRAY[", "]::integer[]") { stored(it).toString() } + else "'" + json(value) + "'" + + override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { + if (value is Array<*>) { + @Suppress("UNCHECKED_CAST") + stmt.setArray(index, "integer", value as Array) + } else { + super.setParameter(stmt, index, value) + } + } +} + +/** Column builder for an int-backed `field.enum` array: a `Column>` of member symbols over `integer[]` / JSON text. */ +internal fun Table.intBackedEnumArray(name: String, intByMember: Map): Column> = + registerColumn(name, IntBackedEnumArrayColumnType(intByMember)) diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntEnumArrayTable.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntEnumArrayTable.kt new file mode 100644 index 0000000000..444e6eddd0 --- /dev/null +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/IntEnumArrayTable.kt @@ -0,0 +1,16 @@ +package com.metaobjects.integration.kotlin.tables + +import org.jetbrains.exposed.sql.Table + +/** + * Hand-written reference Exposed table for the `IntEnumArray` entity (`int_enum_arrays`), the subject of + * the `roundtrip-int-enum-array` scenario: a scalar and an array column that share one inherited + * `@intValueMap`. Both are nullable, matching the canonical DDL. + */ +internal object IntEnumArrayTable : Table("int_enum_arrays") { + val id = long("id").autoIncrement() + val state = intBackedEnum("state", INT_ENUM_MEMBERS).nullable() + val history = intBackedEnumArray("history", INT_ENUM_MEMBERS).nullable() + + override val primaryKey = PrimaryKey(id) +} From 48862e4cfa0e9b68cde0ee8f2045a5565fb35e92 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 21:56:07 -0500 Subject: [PATCH 6/8] feat(maven-plugin): add the init goal mvn metaobjects:init writes the port-neutral .metaobjects/config.json and an empty loadable metaobjects/meta.app.json, each only when missing, and prints the plugin entry to add to the pom with an empty generators list. -Dmeta.init.withDocs=true is the opt-in that adds the api reference generator to the printed entry. It never edits the pom. --- CHANGELOG.md | 7 + docs/features/cli.md | 1 + docs/ports/java.md | 8 + .../java/com/metaobjects/mojo/InitMojo.java | 150 ++++++++++++++++++ .../com/metaobjects/mojo/InitMojoTest.java | 88 ++++++++++ 5 files changed, 254 insertions(+) create mode 100644 server/java/maven-plugin/src/main/java/com/metaobjects/mojo/InitMojo.java create mode 100644 server/java/maven-plugin/src/test/java/com/metaobjects/mojo/InitMojoTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index d34ba6f787..560d541db0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -288,6 +288,13 @@ Each item below is described in full under Security, Added, Changed or Fixed; th ### Added +- **Java and Kotlin: `mvn metaobjects:init`.** The Maven plugin now has the scaffold goal the other + ports have. It writes `.metaobjects/config.json` (the new-project settings every port's init + writes) and an empty, loadable `metaobjects/meta.app.json`, each only when missing, and prints the + `` entry to add to the pom with an empty ``: codegen stays opt-in + (ADR-0034 Amendment 2). `-Dmeta.init.withDocs=true` adds the api reference generator to that + printed entry. It never edits the pom. + - **The hash manifest is one file per package (ADR-0064 Amendment 1).** Every port that keeps hash state, TypeScript, C#, Java, Kotlin, Python and Rust, writes `.gen-state/.hashes/.json` instead of one `.gen-state/.hashes.json`. The file name is the package's `::` segments joined with diff --git a/docs/features/cli.md b/docs/features/cli.md index 2cb7085229..5e7fdf70f6 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -39,6 +39,7 @@ command surface splits in two: | TS codegen | Node `meta` | `meta gen` | TS projects. **No `--template-spec` flag, deliberately** — `metaobjects.config.ts` already takes generator VALUES, so a declarative template generator is declared there (`templateGenerator()`, or `templateSpecToGenerators(parseTemplateSpec(spec))` to reuse a C#/Python spec file). Keeping it in the config is what lets `meta verify --codegen` regenerate WITH it, since that gate re-runs the config's generator list; see [declarative template scopes](codegen-concepts.md#declarative-template-scopes) | | C# codegen | `dotnet meta` | `dotnet meta init` / `gen` / `verify --templates` / `verify --codegen` | a .NET tool (`ToolCommandName=dotnet-meta`); invoked `dotnet meta` so it never shadows the Node `meta`; ships the ADR-0021 D2 subverbs (`--db` rejected, exit 2; bare `verify` = `--templates` plus `--codegen` when an output directory (`csharp.outDir` in `.metaobjects/config.json`, or `--out`) and `codegen/Generators.cs` are present). **The generator list is `codegen/Generators.cs`** (ADR-0034 Amendment 9): `dotnet meta init` writes it with `codegen/Program.cs` (two lines that run it) and `codegen/Codegen.csproj`, and `gen` / `verify --codegen` always run it through `dotnet run --project codegen`. With no `codegen/Generators.cs` they exit 2 and write nothing; `--generators` only narrows the list to declared entries. Every entry may set its own output directory (`ApiDocsGenerator { OutDir = ... }`), and `verify --codegen` compares each one. A declarative Mustache template-spec (the cross-port JSON contract shared with Python) is one more entry, `TemplateSpecGenerator { Spec = "", TemplateRoot = "" }`; `gen` no longer reads `--template-spec` or a project-root `template-spec.json`, and a run that finds either with no such entry fails before writing anything; see [declarative template scopes](codegen-concepts.md#declarative-template-scopes). `dotnet meta docs` was removed in 1.1.0: it prints the line that points at [the migration section](migrations/docs-are-generators.md#c) and exits 2 | | Java/Kotlin codegen | Maven plugin | `mvn metaobjects:generate` (`metaobjects:generate`) | Kotlin generators run through the same goal — see below. **No `--template-spec` flag, deliberately** — `` already loads a consumer class from the project classpath, so the declarative surface is `com.metaobjects.generator.template.TemplateScopeGenerator` wired as an ordinary `` with `