diff --git a/CHANGELOG.md b/CHANGELOG.md index c51315058..adbb601d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1652,6 +1652,20 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru (`writeInstantTzSupport` and its siblings); an owned copy ejected at an earlier version carries its own and still compiles (`EjectedAtBaseGeneratorsCompatTest`). +- **The Kotlin Spring controller writes through `KotlinWriter`** (ADR-0063): the writable + controller, the TPH base controller and the read-only (projection and report) controller, with + the filter pipeline, the M:N traversal routes, the sort surface and the credential redactor they + share. Its entry leaves the layout ratchet's allowlist. **Its output changes in layout only:** + imports in one sorted group, no blank line at the start or end of the controller class, one blank + line where the TPH controller wrote two (before its exception handlers), and two + bodies the old text builder indented one level off now indented by their blocks (the Exposed 1.x + `WhereOp` loop, and a PATCH handler whose only automatic column is an `@autoSet` one). + Regenerating shows those diffs and nothing else. The `protected open` hooks an `open` subclass + overrides (`emitFilterPipeline`, `emitPerFieldDispatchArm`, `emitTypedCoercer`, + `emitM2mEndpoint`, `emitTphSubtypeM2mEndpoint`) now take a `KotlinWriter` where they took a + `StringBuilder`; an owned copy ejected at an earlier version carries its own and still compiles + (`EjectedAtBaseGeneratorsCompatTest`). + - **Python publishes a shared model (FR-023).** A `shared-model` generator, wired in `metaobjects.config.yaml` like any other (`metaobjects gen --list` names its options), writes `.metaobjects.json` and `metaobjects.pkg.json` for a consumer's `deps sync`: `name` and 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 45a1e60ed..4327ebe00 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 @@ -252,7 +252,7 @@ corpus today; opens when a real consumer needs it. ## `ObjectField` skipped in sort allowlist + `rowTo` mapping -**Status:** Day-1 limitation in [`KotlinSpringControllerGenerator.kt:228`](src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt#L228). +**Status:** Day-1 limitation in [`KotlinSpringControllerGenerator.kt`](src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt) (the sort allowlist and the `rowTo` mapper; search for `Sort allowlist`). A `field.object` (jsonb or flattened storage) is not eligible for `?sort=` in the generated controller and is skipped in the `rowTo(...)` mapper diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index e8ff2c477..46f2e5720 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -16,6 +16,7 @@ import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.KotlinTphPlan import com.metaobjects.generator.kotlin.KotlinTypeMapper import com.metaobjects.generator.kotlin.PackageMapping +import com.metaobjects.generator.kotlin.writer.KotlinWriter import com.metaobjects.field.BooleanField import com.metaobjects.field.CurrencyField @@ -93,12 +94,9 @@ import com.metaobjects.generator.util.GeneratedFileWriter * {@link KotlinSpringConfigGenerator}) wires {@code Database.connect()}; the controller * does not own a {@code DataSource} itself. * - *

Substrate justification (hand-rolled string builder rather than KotlinPoet): same - * trade-off as {@link KotlinExposedTableGenerator}. Spring annotations + the Exposed DSL - * (e.g. {@code AuthorTable.selectAll().where { AuthorTable.id eq id }}) don't translate - * cleanly to KotlinPoet's {@code PropertySpec}/{@code FunSpec} APIs without a verbose - * dance of {@code %T} placeholders; the syntactic surface is small (~80 lines per file) - * and matches the idiomatic Kotlin/Spring style. + *

The file is written through [KotlinWriter] (ADR-0063): the generator states each line and + * opens and closes each block, and the writer owns the indentation, the blank lines and the + * import section. * *

Args: *

    @@ -131,17 +129,17 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseKnownFields`: every declared field name, as named on the wire (only under `reject`). */ - private fun StringBuilder.appendKnownFields(shortName: String, names: Collection) { + private fun appendKnownFields(w: KotlinWriter, shortName: String, names: Collection) { if (!rejectUnknown) return - append("/** GENERATED — every field ${shortName} declares, as named on the wire: a body key outside it is refused. */\n") - append("private val ${shortName}KnownFields: Set = setOf(${names.distinct().joinToString(", ") { "\"$it\"" }})\n\n") + w.line("/** GENERATED — every field ${shortName} declares, as named on the wire: a body key outside it is refused. */") + w.line("private val ${shortName}KnownFields: Set = setOf(${names.distinct().joinToString(", ") { "\"$it\"" }})").blank() } /** The unknown-key check of a write handler (after the non-object-body answer), only under `reject`. */ - private fun StringBuilder.appendUnknownGuard(shortName: String) { + private fun appendUnknownGuard(w: KotlinWriter, shortName: String) { if (!rejectUnknown) return - append(" val unknownKeys = MetaUnknownBodyKeys.refusal(body, ${shortName}KnownFields)\n") - append(" if (unknownKeys != null) return@transaction ResponseEntity.badRequest().body(unknownKeys as Any)\n") + w.line("val unknownKeys = MetaUnknownBodyKeys.refusal(body, ${shortName}KnownFields)") + w.line("if (unknownKeys != null) return@transaction ResponseEntity.badRequest().body(unknownKeys as Any)") } /** @@ -149,10 +147,10 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase ${page.maxLimit()}L) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"limit_too_large\", \"maxLimit\" to ${page.maxLimit()}L) as Any)\n") + w.line("if (limit != null && limit < 0) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"limit\", \"value\" to limit.toString(), \"expected\" to \"a non-negative integer (0 or more)\") as Any)") + w.line("if (limit != null && limit > ${page.maxLimit()}L) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"limit_too_large\", \"maxLimit\" to ${page.maxLimit()}L) as Any)") } /** The page size a list handler uses when `limit` is omitted. */ @@ -275,12 +273,12 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase, strips: Boolean) { - if (strips) appendStripCredentials(sb) + private fun appendRedactor(w: KotlinWriter, shortName: String, creds: Collection, strips: Boolean) { + if (strips) appendStripCredentials(w) if (creds.isEmpty()) return - sb.append("/** GENERATED — the ${shortName} response value with its credential field(s) removed. */\n") - sb.append("private fun redact${shortName}(mapper: ObjectMapper, row: ${shortName}): Any =\n") - sb.append(" stripCredentials(mapper, row, ${creds.joinToString(", ") { "\"$it\"" }})\n\n") + w.line("/** GENERATED — the ${shortName} response value with its credential field(s) removed. */") + w.line("private fun redact${shortName}(mapper: ObjectMapper, row: ${shortName}): Any =") + w.indented { w.line("stripCredentials(mapper, row, ${creds.joinToString(", ") { "\"$it\"" }})") }.blank() } /** @@ -292,62 +290,61 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase, List>, Set>() + + /** + * GENERATED — #484: [row] as a JSON tree with its credential properties [hidden] removed, under the keys + * [mapper] actually writes them with (a naming strategy, mixin or @JsonProperty is honoured), plus any key + * that spells one ignoring case, `_` and `-`. Throws rather than send a row it cannot strip. + */ + private fun stripCredentials(mapper: ObjectMapper, row: Any, vararg hidden: String): com.fasterxml.jackson.databind.node.ObjectNode { + val node = mapper.valueToTree(row) + node.remove(credentialWireKeys.computeIfAbsent(Triple(mapper, row.javaClass, hidden.toList())) { credentialKeysOf(mapper, row.javaClass, hidden) }) + val spelled = hidden.map { normalizedKey(it) }.toSet() + node.remove(node.fieldNames().asSequence().filter { normalizedKey(it) in spelled }.toList()) + return node + } + + /** GENERATED — #484: the JSON keys [mapper] writes the credential properties [hidden] of [type] under. */ + private fun credentialKeysOf(mapper: ObjectMapper, type: Class<*>, hidden: Array): Set { + val desc: com.fasterxml.jackson.databind.BeanDescription = mapper.serializationConfig.introspect(mapper.constructType(type)) + val serializer = try { + mapper.serializerProviderInstance.findValueSerializer(type) + } catch (e: com.fasterxml.jackson.databind.JsonMappingException) { + throw unstrippable(type, hidden.toList(), "the mapper has no serializer for it", e) + } + if (serializer !is com.fasterxml.jackson.databind.ser.std.BeanSerializerBase) { + throw unstrippable(type, hidden.toList(), "its serializer is not a bean serializer (a custom serializer?)", null) + } + val keys = HashSet() + for (name in hidden) { + val matched = desc.findProperties().filter { it.internalName == name }.map { it.name } + if (matched.isEmpty() && declaresMember(type, name) && name !in desc.ignoredPropertyNames) { + throw unstrippable(type, listOf(name), "the credential has no property in the mapper's contract", null) + } + keys += matched + } + return keys + } + + private fun declaresMember(type: Class<*>, name: String): Boolean = + generateSequence(type) { it.superclass }.takeWhile { it != Any::class.java }.any { c -> c.declaredFields.any { it.name == name } } + + private fun normalizedKey(key: String): String = key.replace("_", "").replace("-", "").lowercase() + + private fun unstrippable(type: Class<*>, credentials: List, why: String, cause: Throwable?): IllegalStateException = + IllegalStateException( + "cannot strip the credential " + credentials.joinToString(", ") { type.simpleName + "." + it } + " from a response: " + why + + ". Credential stripping reads the ObjectMapper's serialization contract; the response is refused rather than sent unstripped.", + cause, + ) """ - |/** GENERATED — #484: the wire keys of each row class's credentials, read once from the mapper's contract. */ - |private val credentialWireKeys = java.util.concurrent.ConcurrentHashMap, List>, Set>() - | - |/** - | * GENERATED — #484: [row] as a JSON tree with its credential properties [hidden] removed, under the keys - | * [mapper] actually writes them with (a naming strategy, mixin or @JsonProperty is honoured), plus any key - | * that spells one ignoring case, `_` and `-`. Throws rather than send a row it cannot strip. - | */ - |private fun stripCredentials(mapper: ObjectMapper, row: Any, vararg hidden: String): com.fasterxml.jackson.databind.node.ObjectNode { - | val node = mapper.valueToTree(row) - | node.remove(credentialWireKeys.computeIfAbsent(Triple(mapper, row.javaClass, hidden.toList())) { credentialKeysOf(mapper, row.javaClass, hidden) }) - | val spelled = hidden.map { normalizedKey(it) }.toSet() - | node.remove(node.fieldNames().asSequence().filter { normalizedKey(it) in spelled }.toList()) - | return node - |} - | - |/** GENERATED — #484: the JSON keys [mapper] writes the credential properties [hidden] of [type] under. */ - |private fun credentialKeysOf(mapper: ObjectMapper, type: Class<*>, hidden: Array): Set { - | val desc: com.fasterxml.jackson.databind.BeanDescription = mapper.serializationConfig.introspect(mapper.constructType(type)) - | val serializer = try { - | mapper.serializerProviderInstance.findValueSerializer(type) - | } catch (e: com.fasterxml.jackson.databind.JsonMappingException) { - | throw unstrippable(type, hidden.toList(), "the mapper has no serializer for it", e) - | } - | if (serializer !is com.fasterxml.jackson.databind.ser.std.BeanSerializerBase) { - | throw unstrippable(type, hidden.toList(), "its serializer is not a bean serializer (a custom serializer?)", null) - | } - | val keys = HashSet() - | for (name in hidden) { - | val matched = desc.findProperties().filter { it.internalName == name }.map { it.name } - | if (matched.isEmpty() && declaresMember(type, name) && name !in desc.ignoredPropertyNames) { - | throw unstrippable(type, listOf(name), "the credential has no property in the mapper's contract", null) - | } - | keys += matched - | } - | return keys - |} - | - |private fun declaresMember(type: Class<*>, name: String): Boolean = - | generateSequence(type) { it.superclass }.takeWhile { it != Any::class.java }.any { c -> c.declaredFields.any { it.name == name } } - | - |private fun normalizedKey(key: String): String = key.replace("_", "").replace("-", "").lowercase() - | - |private fun unstrippable(type: Class<*>, credentials: List, why: String, cause: Throwable?): IllegalStateException = - | IllegalStateException( - | "cannot strip the credential " + credentials.joinToString(", ") { type.simpleName + "." + it } + " from a response: " + why + - | ". Credential stripping reads the ObjectMapper's serialization contract; the response is refused rather than sent unstripped.", - | cause, - | ) - | - | - """.trimMargin() ) + w.blank() } private fun credentialNames(fields: Collection>): List = @@ -468,160 +465,309 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase traversal sub-resources. val m2mNavs = KotlinM2mSupport.resolve(entity, loader, providedEnums) - val source = buildString { - if (pkg.isNotEmpty()) { - append("package $pkg\n\n") - } - append("import ${ExposedImports.core(api, "Op")}\n") - append("import ${ExposedImports.core(api, "SortOrder")}\n") - append("import ${ExposedImports.core(api, "ResultRow")}\n") - // issue #390 (review fix): under 1.x, SqlExpressionBuilder is gone — every operator - // the filter-pipeline's WhereOp (and delete's bare `eq`) got for free through - // `with(SqlExpressionBuilder) { ... }` is now a plain top-level import, scoped to - // exactly what this entity's scalarFields will make emitFilterPipeline emit — see - // v1FilterOperatorImports. - if (api == ExposedApi.V1) { - for (op in v1FilterOperatorImports(scalarFields)) append("import ${ExposedImports.core(api, op)}\n") + val w = KotlinWriter().packageName(pkg) + w.use(ExposedImports.core(api, "Op")) + w.use(ExposedImports.core(api, "SortOrder")) + w.use(ExposedImports.core(api, "ResultRow")) + // issue #390 (review fix): under 1.x, SqlExpressionBuilder is gone — every operator + // the filter-pipeline's WhereOp (and delete's bare `eq`) got for free through + // `with(SqlExpressionBuilder) { ... }` is now a plain top-level import, scoped to + // exactly what this entity's scalarFields will make emitFilterPipeline emit — see + // v1FilterOperatorImports. + if (api == ExposedApi.V1) { + for (op in v1FilterOperatorImports(scalarFields)) w.use(ExposedImports.core(api, op)) + } else { + w.use("org.jetbrains.exposed.sql.SqlExpressionBuilder") + } + w.use(ExposedImports.core(api, "and")) + w.use(ExposedImports.jdbc(api, "deleteWhere")) + w.use(ExposedImports.jdbc(api, "insert")) + w.use(ExposedImports.jdbc(api, "selectAll")) + w.use(ExposedImports.jdbc(api, "update")) + w.use(ExposedImports.transactions(api, "transaction")) + w.use("com.fasterxml.jackson.databind.JsonNode") + // ObjectMapper + TypeReference are used ONLY by the per-field patch bind, which is + // emitted only when there ARE settable fields — omit them otherwise (unused import / + // ctor param would fail the module's allWarningsAsErrors compile). + if (hasPatchFields) w.use("com.fasterxml.jackson.core.type.TypeReference") + if (needsMapper) w.use("com.fasterxml.jackson.databind.ObjectMapper") + // FR-036: the controller enforces the entity's field constraints over HTTP through a + // jakarta Validator (POST body + present PATCH values) — always injected in this + // writable-table path (a read-only projection controller never reaches emit()). + w.use("jakarta.validation.Validator") + w.use("org.springframework.http.HttpStatus") + w.use("org.springframework.http.ResponseEntity") + w.use("org.springframework.web.bind.annotation.DeleteMapping") + w.use("org.springframework.web.bind.annotation.ExceptionHandler") + w.use("org.springframework.web.bind.annotation.GetMapping") + w.use("org.springframework.web.bind.annotation.PathVariable") + w.use("org.springframework.web.bind.annotation.PostMapping") + w.use("org.springframework.web.bind.annotation.RequestBody") + w.use("org.springframework.web.bind.annotation.RequestMapping") + w.use("org.springframework.web.bind.annotation.RequestMethod") + w.use("org.springframework.web.bind.annotation.RequestParam") + w.use("org.springframework.web.bind.annotation.RestController") + w.use("jakarta.servlet.http.HttpServletRequest") + w.use("java.io.ByteArrayOutputStream") + w.use("java.nio.charset.StandardCharsets") + w.use("java.sql.Timestamp") + // ADR-0036 Wave 2: a default field.timestamp column maps to java.time.Instant + // (the WHERE-arm casts `p.value as Instant`); import it only when such a column + // is present so entities without one stay byte-identical. + if (scalarFields.any { it.elementType == "Instant" }) { + w.use("java.time.Instant") + } + // A uuid PK / uuid scalar column surfaces java.util.UUID in the by-id route + // signatures and the filter-dispatch casts; import it only when present so + // uuid-free entities stay byte-identical. + if (pkParamType == "UUID" || scalarFields.any { it.elementType == "UUID" }) { + w.use("java.util.UUID") + } + // Pre-existing gap found while adding issue #390's controller-tier compile pass + // (review fix #2): a filterable field.decimal's WHERE-arm casts `p.value as + // BigDecimal` (see emitPerFieldDispatchArm) with no import anywhere in this file — + // "Unresolved reference: BigDecimal" on BOTH exposedApi values (this generator never + // excludes DecimalField from scalarFields the way emitTph's filterSpecs does; no + // existing test compiled this entity+controller combination to catch it). Fixed for + // both: nothing depends on broken, never-compiled output, so there is no + // byte-identical contract to preserve here. Same conditional-import shape as + // Instant/UUID above. + if (scalarFields.any { it.elementType == "BigDecimal" }) { + w.use("java.math.BigDecimal") + } + // Same pre-existing gap, same fix, for a filterable field.uri / field.inet (a + // @lenient one degrades to String — see KotlinTypeMapper.lenientNetField — and + // needs neither import, which is exactly why this checks elementType, not subType). + if (scalarFields.any { it.elementType == "URI" }) { + w.use("java.net.URI") + } + if (scalarFields.any { it.elementType == "InetAddress" }) { + w.use("java.net.InetAddress") + } + if (scalarFields.any { it.elementType == "Duration" }) { + w.use("java.time.Duration") + } + // FR-009 (#179): a filterable enum column is compared as its stored string via + // `col.castTo(TextColumnType())`; import both only when such a column exists + // so entities without a filterable enum stay byte-identical. + if (scalarFields.any { needsStringCastDispatch(it.subType, it.elementType, it.intBackedEnumType) }) { + w.use(ExposedImports.core(api, "TextColumnType")) + w.use(ExposedImports.core(api, "castTo")) + } + w.use("java.time.LocalDate") + w.use("java.time.LocalDateTime") + w.use("java.time.LocalTime") + w.use("java.time.format.DateTimeFormatter") + for (line in KotlinM2mSupport.importLines(m2mNavs, pkg, junction = false, dataClass = true)) { + w.use("$line") + } + w.blank() + appendSortSurface(w, shortName, entity, sortFields) + appendKnownFields(w, shortName, entity.metaFields.map { it.name }) + + // FR-009 filter pipeline. Three stages: + // 1. data class ${shortName}FilterPredicate — parsed + validated one + // filter[][]= entry (value already coerced to a Kotlin type). + // 2. parse${shortName}Filter — walks the raw query string (decoded per + // component, tolerating a malformed escape), matching the grammar against + // ${allowlistName}.FIELDS + .OPS_BY_FIELD. Returns either predicates or + // one of the cross-port error envelope keys. + // 3. ${shortName}WhereOp — converts the predicate list into an Exposed + // Op bound against ${tableObjectName}'s columns. Multiple + // predicates AND together. Per-field arms know each column's Kotlin + // type at compile time (no reflection / runtime cast surprises). + // #214: the filter + sort surface reads through the READ object (the view for a + // write-through entity), so its per-field Exposed dispatch binds against `readObj`. + emitFilterPipeline(w, shortName, readObj, allowlistName, scalarFields) + + appendRowToMapper(w, shortName, entity, readObj) + appendRedactor(w, shortName, creds, strips) + + w.line("/**") + w.line(" * GENERATED — REST controller for ${shortName} entity. Implements the cross-port API contract.") + w.line(" *") + // No `/**` glob in the example: Kotlin NESTS block comments, so a `/*` inside this + // KDoc would open a comment that never closes and the file would not compile. + w.line(" * Auth: these endpoints are unauthenticated. In your Spring Security config, require") + w.line(" * authentication for `$routeBase` and every path under it (`requestMatchers` + `authenticated()`).") + w.line(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path") + w.line(" * config — eject this generator with `mvn metaobjects:eject` and hand-write those endpoints.") + w.line(" */") + w.line("@RestController") + w.line("@RequestMapping(\"$routeBase\")") + // FR-036: `validator` is always injected (POST + present-PATCH-value enforcement). + // FR-035 present-key PATCH: the update handler binds the RAW JsonNode (not a + // @Valid data class, which cannot see absent-vs-null) and per-field-binds present + // values via the Spring-configured ObjectMapper — injected only when there ARE + // settable fields (a PK + only object/jsonb columns needs no mapper). + if (needsMapper) { + w.open("class ${shortName}Controller(private val objectMapper: ObjectMapper, private val validator: Validator) {").blank() + } else { + w.open("class ${shortName}Controller(private val validator: Validator) {").blank() + } + + appendListHandler(w, shortName, readObj, sortFields, creds) + + appendGetHandler(w, shortName, readObj, pkFieldName, pkParamType, creds) + + // POST — create. FR-036: validate the bound body through the jakarta Validator and + // 400 with the cross-port envelope on any violation BEFORE the insert. (@Valid's + // default 400 body is NOT the cross-port {error:"validation"} shape and does not fire + // under MockMvc standaloneSetup — so the check is explicit here.) + w.line("@PostMapping") + val patchKtType = { field: MetaField<*> -> + val elem: String = if (field is ObjectField) { + voElementTypeFqn(field, loader) + } else if (field is MapField) { + "kotlin.collections.Map" } else { - append("import org.jetbrains.exposed.sql.SqlExpressionBuilder\n") - } - append("import ${ExposedImports.core(api, "and")}\n") - append("import ${ExposedImports.jdbc(api, "deleteWhere")}\n") - append("import ${ExposedImports.jdbc(api, "insert")}\n") - append("import ${ExposedImports.jdbc(api, "selectAll")}\n") - append("import ${ExposedImports.jdbc(api, "update")}\n") - append("import ${ExposedImports.transactions(api, "transaction")}\n") - append("import com.fasterxml.jackson.databind.JsonNode\n") - // ObjectMapper + TypeReference are used ONLY by the per-field patch bind, which is - // emitted only when there ARE settable fields — omit them otherwise (unused import / - // ctor param would fail the module's allWarningsAsErrors compile). - if (hasPatchFields) append("import com.fasterxml.jackson.core.type.TypeReference\n") - if (needsMapper) append("import com.fasterxml.jackson.databind.ObjectMapper\n") - // FR-036: the controller enforces the entity's field constraints over HTTP through a - // jakarta Validator (POST body + present PATCH values) — always injected in this - // writable-table path (a read-only projection controller never reaches emit()). - append("import jakarta.validation.Validator\n") - append("import org.springframework.http.HttpStatus\n") - append("import org.springframework.http.ResponseEntity\n") - append("import org.springframework.web.bind.annotation.DeleteMapping\n") - append("import org.springframework.web.bind.annotation.ExceptionHandler\n") - append("import org.springframework.web.bind.annotation.GetMapping\n") - append("import org.springframework.web.bind.annotation.PathVariable\n") - append("import org.springframework.web.bind.annotation.PostMapping\n") - append("import org.springframework.web.bind.annotation.RequestBody\n") - append("import org.springframework.web.bind.annotation.RequestMapping\n") - append("import org.springframework.web.bind.annotation.RequestMethod\n") - append("import org.springframework.web.bind.annotation.RequestParam\n") - append("import org.springframework.web.bind.annotation.RestController\n") - append("import jakarta.servlet.http.HttpServletRequest\n") - append("import java.io.ByteArrayOutputStream\n") - append("import java.nio.charset.StandardCharsets\n") - append("import java.sql.Timestamp\n") - // ADR-0036 Wave 2: a default field.timestamp column maps to java.time.Instant - // (the WHERE-arm casts `p.value as Instant`); import it only when such a column - // is present so entities without one stay byte-identical. - if (scalarFields.any { it.elementType == "Instant" }) { - append("import java.time.Instant\n") - } - // A uuid PK / uuid scalar column surfaces java.util.UUID in the by-id route - // signatures and the filter-dispatch casts; import it only when present so - // uuid-free entities stay byte-identical. - if (pkParamType == "UUID" || scalarFields.any { it.elementType == "UUID" }) { - append("import java.util.UUID\n") - } - // Pre-existing gap found while adding issue #390's controller-tier compile pass - // (review fix #2): a filterable field.decimal's WHERE-arm casts `p.value as - // BigDecimal` (see emitPerFieldDispatchArm) with no import anywhere in this file — - // "Unresolved reference: BigDecimal" on BOTH exposedApi values (this generator never - // excludes DecimalField from scalarFields the way emitTph's filterSpecs does; no - // existing test compiled this entity+controller combination to catch it). Fixed for - // both: nothing depends on broken, never-compiled output, so there is no - // byte-identical contract to preserve here. Same conditional-import shape as - // Instant/UUID above. - if (scalarFields.any { it.elementType == "BigDecimal" }) { - append("import java.math.BigDecimal\n") - } - // Same pre-existing gap, same fix, for a filterable field.uri / field.inet (a - // @lenient one degrades to String — see KotlinTypeMapper.lenientNetField — and - // needs neither import, which is exactly why this checks elementType, not subType). - if (scalarFields.any { it.elementType == "URI" }) { - append("import java.net.URI\n") + (KotlinTypeMapper.enumTypeName(field, entity, providedEnums) ?: KotlinTypeMapper.kotlinTypeName(field)).toString() } - if (scalarFields.any { it.elementType == "InetAddress" }) { - append("import java.net.InetAddress\n") - } - if (scalarFields.any { it.elementType == "Duration" }) { - append("import java.time.Duration\n") - } - // FR-009 (#179): a filterable enum column is compared as its stored string via - // `col.castTo(TextColumnType())`; import both only when such a column exists - // so entities without a filterable enum stay byte-identical. - if (scalarFields.any { needsStringCastDispatch(it.subType, it.elementType, it.intBackedEnumType) }) { - append("import ${ExposedImports.core(api, "TextColumnType")}\n") - append("import ${ExposedImports.core(api, "castTo")}\n") + if (field.isArrayType) "kotlin.collections.List<$elem>" else elem + } + if (hasPatchFields) { + // Bind the raw body so a body Jackson cannot bind as a whole (a required value missing) still + // gets EVERY issue listed: on a failed bind each present field is bound and validated on its own, + // and the failure itself is added at the field it names. + w.open("fun create(@RequestBody body: JsonNode): ResponseEntity = transaction {") + w.line("val issues = MetaValidationIssues.Collector()") + w.line("if (!body.isObject) return@transaction ResponseEntity.badRequest().body(issues.add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)") + appendUnknownGuard(w, shortName) + w.open("val dto: ${shortName} = try {") + w.line("objectMapper.treeToValue(body, ${shortName}::class.java)") + w.reopen("} catch (e: Exception) {") + // A required value with no default that is absent or null cannot bind: list EACH one here, since + // Jackson names only the first it meets. + for (field in patchSettableFields) { + if (KotlinGenUtil.isRequiredField(field) && !field.hasMetaAttr(MetaField.ATTR_DEFAULT) && + !KotlinGenUtil.isServerOwnedOnCreate(field, entity) && !KotlinGenUtil.isNullableShapeProperty(field) && + !KotlinGenUtil.isDerivedField(field) + ) { + w.line("if (!body.has(\"${field.name}\") || body.get(\"${field.name}\").isNull) issues.add(\"invalid_type\", listOf(\"${field.name}\"), \"field '${field.name}' is required\")") + } } - append("import java.time.LocalDate\n") - append("import java.time.LocalDateTime\n") - append("import java.time.LocalTime\n") - append("import java.time.format.DateTimeFormatter\n") - for (line in KotlinM2mSupport.importLines(m2mNavs, pkg, junction = false, dataClass = true)) { - append("import $line\n") + for (field in patchSettableFields) { + val fn = field.name + val cap = capitalizeFirst(fn) + val kt = patchKtType(field) + w.open("if (body.has(\"$fn\") && !body.get(\"$fn\").isNull) {") + w.line("val v$cap: $kt? = issues.bind<$kt>(\"$fn\") { ${patchBindExpr(field, fn, kt)} }") + w.line("if (v$cap != null) issues.addAt(validator.validateValue(${shortName}::class.java, \"$fn\", v$cap), \"$fn\")") + appendDecimalRangeCheck(w, field, "v$cap") + w.close("}") } - append("\n") - appendSortSurface(this, shortName, entity, sortFields) - appendKnownFields(shortName, entity.metaFields.map { it.name }) - - // FR-009 filter pipeline. Three stages: - // 1. data class ${shortName}FilterPredicate — parsed + validated one - // filter[][]= entry (value already coerced to a Kotlin type). - // 2. parse${shortName}Filter — walks the raw query string (decoded per - // component, tolerating a malformed escape), matching the grammar against - // ${allowlistName}.FIELDS + .OPS_BY_FIELD. Returns either predicates or - // one of the cross-port error envelope keys. - // 3. ${shortName}WhereOp — converts the predicate list into an Exposed - // Op bound against ${tableObjectName}'s columns. Multiple - // predicates AND together. Per-field arms know each column's Kotlin - // type at compile time (no reflection / runtime cast surprises). - // #214: the filter + sort surface reads through the READ object (the view for a - // write-through entity), so its per-field Exposed dispatch binds against `readObj`. - emitFilterPipeline(this, shortName, readObj, allowlistName, scalarFields) - - appendRowToMapper(this, shortName, entity, readObj) - appendRedactor(this, shortName, creds, strips) - - append("/**\n") - append(" * GENERATED — REST controller for ${shortName} entity. Implements the cross-port API contract.\n") - append(" *\n") - // No `/**` glob in the example: Kotlin NESTS block comments, so a `/*` inside this - // KDoc would open a comment that never closes and the file would not compile. - append(" * Auth: these endpoints are unauthenticated. In your Spring Security config, require\n") - append(" * authentication for `$routeBase` and every path under it (`requestMatchers` + `authenticated()`).\n") - append(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path\n") - append(" * config — eject this generator with `mvn metaobjects:eject` and hand-write those endpoints.\n") - append(" */\n") - append("@RestController\n") - append("@RequestMapping(\"$routeBase\")\n") - // FR-036: `validator` is always injected (POST + present-PATCH-value enforcement). - // FR-035 present-key PATCH: the update handler binds the RAW JsonNode (not a - // @Valid data class, which cannot see absent-vs-null) and per-field-binds present - // values via the Spring-configured ObjectMapper — injected only when there ARE - // settable fields (a PK + only object/jsonb columns needs no mapper). - if (needsMapper) { - append("class ${shortName}Controller(private val objectMapper: ObjectMapper, private val validator: Validator) {\n\n") - } else { - append("class ${shortName}Controller(private val validator: Validator) {\n\n") + w.line("issues.addFailure(e)") + w.line("return@transaction ResponseEntity.badRequest().body(issues.body() as Any)") + w.close("}") + w.line("issues.addViolations(validator.validate(dto))") + } else if (rejectUnknown) { + // The raw body is read first so an undeclared key is refused whatever the host's ObjectMapper does. + w.open("fun create(@RequestBody body: JsonNode): ResponseEntity = transaction {") + w.line("if (!body.isObject) return@transaction ResponseEntity.badRequest().body(MetaValidationIssues.Collector().add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)") + appendUnknownGuard(w, shortName) + w.open("val dto: ${shortName} = try {") + w.line("objectMapper.treeToValue(body, ${shortName}::class.java)") + w.reopen("} catch (e: Exception) {") + w.line("return@transaction ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any)") + w.close("}") + w.line("val issues = MetaValidationIssues.Collector().addViolations(validator.validate(dto))") + } else { + w.open("fun create(@RequestBody dto: ${shortName}): ResponseEntity = transaction {") + w.line("val issues = MetaValidationIssues.Collector().addViolations(validator.validate(dto))") + } + for (field in entity.metaFields) appendDecimalRangeCheck(w, field, "dto.${field.name}") + // Every issue is listed (never just the first): collected above, answered once. + w.line("if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)") + // #203/ADR-0045: capture one now() per temporal type so createdAt == updatedAt exactly. + for ((expr, valName) in insertNowVal) w.line("val $valName = $expr") + w.open("val newId = ${tableObjectName}.insert {") + // A `@generation: uuid` key is minted HERE, not left to the column's database default: + // Exposed hands back `[Table.id]` only for a value it inserted or an autoIncrement + // column, so a DB-defaulted uuid key read back as "id is not in record set" on every + // driver that will not return it. Minting app-side is what the TS runtime does too. + if (uuidGeneratedPk(entity, pkFieldName)) w.line("it[${tableObjectName}.${pkFieldName}] = java.util.UUID.randomUUID()") + for (field in KotlinGenUtil.columnFields(entity)) { + // Program D: a field.object value-object jsonb column IS written on create — the + // DTO property is the typed VO (record / List) and the Exposed Column codec + // encodes it to jsonb. A dict-of-VO MapField is written the same way (Map); a + // scalar-valued MapField stays skipped, and so does a flattened object field (no + // single `Table.`). + if ((field is MapField && !isVoMapColumn(field)) || (field is ObjectField && !isJsonbObjectColumn(field))) continue + // Skip the PK column on insert — the table's @generation=increment owns it. + // If the entity has no auto-incrementing PK the consumer can override the + // generated handler; this is the 95% case. + if (field.name == pkFieldName) continue + // #214: a DERIVED (origin.*) field on a write-through entity has no column on the + // write table (computed by the view), so it is never written on create. + if (writeThrough && KotlinGenUtil.isDerivedField(field)) continue + // #203/ADR-0045: insert stamps onCreate+onUpdate @autoSet columns from the captured + // now() (the caller's value is ignored — never bound from the dto). + if (KotlinGenUtil.isAutoSetField(field)) { + w.line("it[${tableObjectName}.${field.name}] = ${insertNowVal[KotlinTypeMapper.nowExpr(field)]}") + continue } - - appendListHandler(this, shortName, readObj, sortFields, creds) - - appendGetHandler(this, shortName, readObj, pkFieldName, pkParamType, creds) - - // POST — create. FR-036: validate the bound body through the jakarta Validator and - // 400 with the cross-port envelope on any violation BEFORE the insert. (@Valid's - // default 400 body is NOT the cross-port {error:"validation"} shape and does not fire - // under MockMvc standaloneSetup — so the check is explicit here.) - append(" @PostMapping\n") - val patchKtType = { field: MetaField<*> -> + // #484: a @formExclude / credential column is never bound from the request body. + if (KotlinGenUtil.isApiWriteDenied(field)) continue + // A readOnly or derived column is server-owned (the 1.2.x security fix). A client value + // is DROPPED (never 400'd) and the column keeps its default, the same rule as the + // PATCH settable set. + if (KotlinGenUtil.isReadOnlyMutability(field) || KotlinGenUtil.isDerivedField(field)) continue + // NOTE: a `field.string @dbColumnType=jsonb` open bag IS written here (create + // binds it from the @Valid DTO's kotlinx JsonElement property, gated by the + // jsonb-open-bag-roundtrip corpus). PATCH cannot (the raw-JsonNode path can't bind + // a JsonElement without surfacing the un-imported type the #179 guard forbids), so + // an open bag is a create-only column on the generated CRUD — see KNOWN_GAPS. + w.line("it[${tableObjectName}.${field.name}] = dto.${field.name}") + } + w.close("}[${tableObjectName}.${pkFieldName}]") + // #214: re-read the persisted row through the READ object (the view for a write-through + // entity) by PK so the returned entity carries the derived fields (read-your-writes). + w.line("val saved = ${readObj}.selectAll().where { ${readObj}.${pkFieldName} eq newId }.single()") + w.line("ResponseEntity.status(HttpStatus.CREATED).body(${wireRow(shortName, creds, "saved")} as Any)") + w.close("}").blank() + + // PATCH + PUT — single handler (per API contract; same body shape both verbs). + // Both verbs MUST be expressed on one @RequestMapping with method=[PATCH, PUT]. + // Stacking @PatchMapping + @PutMapping on the same method does NOT register both + // in Spring MVC — only one composed @RequestMapping per method is honored, so the + // other verb 405s. (Surfaced by the SP-F generated-controller HTTP lane.) + // FR-035 present-key tristate: bind the RAW JsonNode so absent-vs-null is visible. + // A non-object body, or an explicit null on a @required field, is a 400; an explicit + // null on a nullable field CLEARS it; an omitted field is untouched; a present value + // binds through the configured ObjectMapper (same codecs as create). An empty + // effective patch is a no-op read-back (avoids Exposed's empty-SET error). + // Settable columns are `patchSettableFields` (computed up top): scalar + value-object + // fields minus the PK, EXCLUDING map/jsonb-open-bag (an open bag is a create-only CRUD + // column — PATCH can't bind a kotlinx JsonElement; see KNOWN_GAPS). Program D: a present + // field.object VO binds via Jackson treeToValue and is validated in FULL (spec §0). + // When empty, no update{} block is emitted (an empty Exposed SET throws) — a no-op read-back. + w.line("@RequestMapping(value = [\"/{id}\"], method = [RequestMethod.PATCH, RequestMethod.PUT])") + w.open("fun update(@PathVariable id: $pkParamType, @RequestBody body: JsonNode): ResponseEntity = transaction {") + appendPatchHead(w, patchSettableFields, shortName) + val mustStampOnUpdate = onUpdateAutoSetFields.isNotEmpty() + if (hasPatchFields) { + val settableNamesList = patchSettableFields.joinToString(", ") { "\"${it.name}\"" } + // #203/ADR-0045: with onUpdate @autoSet columns the update must run on EVERY patch + // (to bump them) — no "any present" guard; otherwise the guard keeps the update out + // when the caller sent no settable field (byte-identical to the pre-#203 output). + if (!mustStampOnUpdate) w.open("if (listOf($settableNamesList).any { body.has(it) }) {") + // A present value that cannot bind to its column's Kotlin type (e.g. a JSON object + // for a String column) throws from treeToValue — map that to 400, not a 500. Catch + // the specific Jackson JsonMappingException so no unrelated exception is swallowed. + w.open("run {") + // FR-036: bind each PRESENT value into a typed local, then validate present NON-NULL + // values against the entity's field constraints (validator.validateValue) — a bind + // failure OR a constraint violation → 400 BEFORE any write. Binding happens here (not + // inside the Exposed update{} lambda) so `return@transaction` on a violation is legal + // (a qualified return cannot cross the non-inline update{} lambda). present-null on a + // @required field was already 400'd above; present-null on a nullable field clears it + // (no bind, no validation). + for (field in patchSettableFields) { + // The DATA-CLASS element type: a field.enum's materialized enum class; a + // field.object's referenced value-object record (Program D — bound via Jackson + // treeToValue into the VO / List); else the scalar Kotlin type — so the bound + // value matches the Exposed Column. A VO type is emitted fully-qualified so the + // controller needs no extra import (mirrors the Exposed column codec). val elem: String = if (field is ObjectField) { voElementTypeFqn(field, loader) } else if (field is MapField) { @@ -629,255 +775,103 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase" else elem - } - if (hasPatchFields) { - // Bind the raw body so a body Jackson cannot bind as a whole (a required value missing) still - // gets EVERY issue listed: on a failed bind each present field is bound and validated on its own, - // and the failure itself is added at the field it names. - append(" fun create(@RequestBody body: JsonNode): ResponseEntity = transaction {\n") - append(" val issues = MetaValidationIssues.Collector()\n") - append(" if (!body.isObject) return@transaction ResponseEntity.badRequest().body(issues.add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)\n") - appendUnknownGuard(shortName) - append(" val dto: ${shortName} = try {\n") - append(" objectMapper.treeToValue(body, ${shortName}::class.java)\n") - append(" } catch (e: Exception) {\n") - // A required value with no default that is absent or null cannot bind: list EACH one here, since - // Jackson names only the first it meets. - for (field in patchSettableFields) { - if (KotlinGenUtil.isRequiredField(field) && !field.hasMetaAttr(MetaField.ATTR_DEFAULT) && - !KotlinGenUtil.isServerOwnedOnCreate(field, entity) && !KotlinGenUtil.isNullableShapeProperty(field) && - !KotlinGenUtil.isDerivedField(field) - ) { - append(" if (!body.has(\"${field.name}\") || body.get(\"${field.name}\").isNull) issues.add(\"invalid_type\", listOf(\"${field.name}\"), \"field '${field.name}' is required\")\n") - } - } - for (field in patchSettableFields) { - val fn = field.name - val cap = capitalizeFirst(fn) - val kt = patchKtType(field) - append(" if (body.has(\"$fn\") && !body.get(\"$fn\").isNull) {\n") - append(" val v$cap: $kt? = issues.bind<$kt>(\"$fn\") { ${patchBindExpr(field, fn, kt)} }\n") - append(" if (v$cap != null) issues.addAt(validator.validateValue(${shortName}::class.java, \"$fn\", v$cap), \"$fn\")\n") - appendDecimalRangeCheck(" ", field, "v$cap") - append(" }\n") - } - append(" issues.addFailure(e)\n") - append(" return@transaction ResponseEntity.badRequest().body(issues.body() as Any)\n") - append(" }\n") - append(" issues.addViolations(validator.validate(dto))\n") - } else if (rejectUnknown) { - // The raw body is read first so an undeclared key is refused whatever the host's ObjectMapper does. - append(" fun create(@RequestBody body: JsonNode): ResponseEntity = transaction {\n") - append(" if (!body.isObject) return@transaction ResponseEntity.badRequest().body(MetaValidationIssues.Collector().add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)\n") - appendUnknownGuard(shortName) - append(" val dto: ${shortName} = try {\n") - append(" objectMapper.treeToValue(body, ${shortName}::class.java)\n") - append(" } catch (e: Exception) {\n") - append(" return@transaction ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any)\n") - append(" }\n") - append(" val issues = MetaValidationIssues.Collector().addViolations(validator.validate(dto))\n") - } else { - append(" fun create(@RequestBody dto: ${shortName}): ResponseEntity = transaction {\n") - append(" val issues = MetaValidationIssues.Collector().addViolations(validator.validate(dto))\n") - } - for (field in entity.metaFields) appendDecimalRangeCheck(" ", field, "dto.${field.name}") - // Every issue is listed (never just the first): collected above, answered once. - append(" if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)\n") - // #203/ADR-0045: capture one now() per temporal type so createdAt == updatedAt exactly. - for ((expr, valName) in insertNowVal) append(" val $valName = $expr\n") - append(" val newId = ${tableObjectName}.insert {\n") - // A `@generation: uuid` key is minted HERE, not left to the column's database default: - // Exposed hands back `[Table.id]` only for a value it inserted or an autoIncrement - // column, so a DB-defaulted uuid key read back as "id is not in record set" on every - // driver that will not return it. Minting app-side is what the TS runtime does too. - if (uuidGeneratedPk(entity, pkFieldName)) append(" it[${tableObjectName}.${pkFieldName}] = java.util.UUID.randomUUID()\n") - for (field in KotlinGenUtil.columnFields(entity)) { - // Program D: a field.object value-object jsonb column IS written on create — the - // DTO property is the typed VO (record / List) and the Exposed Column codec - // encodes it to jsonb. A dict-of-VO MapField is written the same way (Map); a - // scalar-valued MapField stays skipped, and so does a flattened object field (no - // single `Table.`). - if ((field is MapField && !isVoMapColumn(field)) || (field is ObjectField && !isJsonbObjectColumn(field))) continue - // Skip the PK column on insert — the table's @generation=increment owns it. - // If the entity has no auto-incrementing PK the consumer can override the - // generated handler; this is the 95% case. - if (field.name == pkFieldName) continue - // #214: a DERIVED (origin.*) field on a write-through entity has no column on the - // write table (computed by the view), so it is never written on create. - if (writeThrough && KotlinGenUtil.isDerivedField(field)) continue - // #203/ADR-0045: insert stamps onCreate+onUpdate @autoSet columns from the captured - // now() (the caller's value is ignored — never bound from the dto). - if (KotlinGenUtil.isAutoSetField(field)) { - append(" it[${tableObjectName}.${field.name}] = ${insertNowVal[KotlinTypeMapper.nowExpr(field)]}\n") - continue + val ktType = if (field.isArrayType) "kotlin.collections.List<$elem>" else elem + val fn = field.name + val cap = capitalizeFirst(fn) + appendPatchFieldBinding(w, field, ktType, patchBindExpr(field, fn, ktType), "${shortName}::class.java") + // Program D (spec §0): jakarta validateValue does NOT cascade @Valid into a nested + // value-object's constraints, so a present VO is validated EXPLICITLY — + // validator.validate(voElement) per element (single VO whole; array VO per element), + // 400 on any violation. (A present-null / cleared value is already handled above.) + if (field is MapField) { + // Each map VALUE is a value object validated on its own (the keys are arbitrary text). + w.line("if (v$cap != null) for ((k, el) in v$cap) issues.addViolations(validator.validate(el), \"$fn\", k)") } - // #484: a @formExclude / credential column is never bound from the request body. - if (KotlinGenUtil.isApiWriteDenied(field)) continue - // A readOnly or derived column is server-owned (the 1.2.x security fix). A client value - // is DROPPED (never 400'd) and the column keeps its default, the same rule as the - // PATCH settable set. - if (KotlinGenUtil.isReadOnlyMutability(field) || KotlinGenUtil.isDerivedField(field)) continue - // NOTE: a `field.string @dbColumnType=jsonb` open bag IS written here (create - // binds it from the @Valid DTO's kotlinx JsonElement property, gated by the - // jsonb-open-bag-roundtrip corpus). PATCH cannot (the raw-JsonNode path can't bind - // a JsonElement without surfacing the un-imported type the #179 guard forbids), so - // an open bag is a create-only column on the generated CRUD — see KNOWN_GAPS. - append(" it[${tableObjectName}.${field.name}] = dto.${field.name}\n") - } - append(" }[${tableObjectName}.${pkFieldName}]\n") - // #214: re-read the persisted row through the READ object (the view for a write-through - // entity) by PK so the returned entity carries the derived fields (read-your-writes). - append(" val saved = ${readObj}.selectAll().where { ${readObj}.${pkFieldName} eq newId }.single()\n") - append(" ResponseEntity.status(HttpStatus.CREATED).body(${wireRow(shortName, creds, "saved")} as Any)\n") - append(" }\n\n") - - // PATCH + PUT — single handler (per API contract; same body shape both verbs). - // Both verbs MUST be expressed on one @RequestMapping with method=[PATCH, PUT]. - // Stacking @PatchMapping + @PutMapping on the same method does NOT register both - // in Spring MVC — only one composed @RequestMapping per method is honored, so the - // other verb 405s. (Surfaced by the SP-F generated-controller HTTP lane.) - // FR-035 present-key tristate: bind the RAW JsonNode so absent-vs-null is visible. - // A non-object body, or an explicit null on a @required field, is a 400; an explicit - // null on a nullable field CLEARS it; an omitted field is untouched; a present value - // binds through the configured ObjectMapper (same codecs as create). An empty - // effective patch is a no-op read-back (avoids Exposed's empty-SET error). - // Settable columns are `patchSettableFields` (computed up top): scalar + value-object - // fields minus the PK, EXCLUDING map/jsonb-open-bag (an open bag is a create-only CRUD - // column — PATCH can't bind a kotlinx JsonElement; see KNOWN_GAPS). Program D: a present - // field.object VO binds via Jackson treeToValue and is validated in FULL (spec §0). - // When empty, no update{} block is emitted (an empty Exposed SET throws) — a no-op read-back. - append(" @RequestMapping(value = [\"/{id}\"], method = [RequestMethod.PATCH, RequestMethod.PUT])\n") - append(" fun update(@PathVariable id: $pkParamType, @RequestBody body: JsonNode): ResponseEntity = transaction {\n") - appendPatchHead(this, patchSettableFields, shortName) - val mustStampOnUpdate = onUpdateAutoSetFields.isNotEmpty() - if (hasPatchFields) { - val settableNamesList = patchSettableFields.joinToString(", ") { "\"${it.name}\"" } - // #203/ADR-0045: with onUpdate @autoSet columns the update must run on EVERY patch - // (to bump them) — no "any present" guard; otherwise the guard keeps the update out - // when the caller sent no settable field (byte-identical to the pre-#203 output). - if (!mustStampOnUpdate) append(" if (listOf($settableNamesList).any { body.has(it) }) {\n") - // A present value that cannot bind to its column's Kotlin type (e.g. a JSON object - // for a String column) throws from treeToValue — map that to 400, not a 500. Catch - // the specific Jackson JsonMappingException so no unrelated exception is swallowed. - append(" run {\n") - // FR-036: bind each PRESENT value into a typed local, then validate present NON-NULL - // values against the entity's field constraints (validator.validateValue) — a bind - // failure OR a constraint violation → 400 BEFORE any write. Binding happens here (not - // inside the Exposed update{} lambda) so `return@transaction` on a violation is legal - // (a qualified return cannot cross the non-inline update{} lambda). present-null on a - // @required field was already 400'd above; present-null on a nullable field clears it - // (no bind, no validation). - for (field in patchSettableFields) { - // The DATA-CLASS element type: a field.enum's materialized enum class; a - // field.object's referenced value-object record (Program D — bound via Jackson - // treeToValue into the VO / List); else the scalar Kotlin type — so the bound - // value matches the Exposed Column. A VO type is emitted fully-qualified so the - // controller needs no extra import (mirrors the Exposed column codec). - val elem: String = if (field is ObjectField) { - voElementTypeFqn(field, loader) - } else if (field is MapField) { - "kotlin.collections.Map" + if (field is ObjectField) { + if (field.isArrayType) { + w.line("if (v$cap != null) v$cap.forEachIndexed { i, el -> issues.addViolations(validator.validate(el), \"$fn\", i) }") } else { - (KotlinTypeMapper.enumTypeName(field, entity, providedEnums) ?: KotlinTypeMapper.kotlinTypeName(field)).toString() - } - val ktType = if (field.isArrayType) "kotlin.collections.List<$elem>" else elem - val fn = field.name - val cap = capitalizeFirst(fn) - appendPatchFieldBinding(this, field, ktType, patchBindExpr(field, fn, ktType), "${shortName}::class.java") - // Program D (spec §0): jakarta validateValue does NOT cascade @Valid into a nested - // value-object's constraints, so a present VO is validated EXPLICITLY — - // validator.validate(voElement) per element (single VO whole; array VO per element), - // 400 on any violation. (A present-null / cleared value is already handled above.) - if (field is MapField) { - // Each map VALUE is a value object validated on its own (the keys are arbitrary text). - append(" if (v$cap != null) for ((k, el) in v$cap) issues.addViolations(validator.validate(el), \"$fn\", k)\n") - } - if (field is ObjectField) { - if (field.isArrayType) { - append(" if (v$cap != null) v$cap.forEachIndexed { i, el -> issues.addViolations(validator.validate(el), \"$fn\", i) }\n") - } else { - append(" if (v$cap != null) issues.addViolations(validator.validate(v$cap), \"$fn\")\n") - } + w.line("if (v$cap != null) issues.addViolations(validator.validate(v$cap), \"$fn\")") } } - // Every issue found above is answered at once, before anything is written. - append(" if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)\n") - // Apply the already-bound + validated values. Columns are qualified (`Table.col`) - // so a field named like the `body`/`id` params can't shadow them. - append(" ${tableObjectName}.update({ ${tableObjectName}.${pkFieldName} eq id }) {\n") - // #203/ADR-0045: bump every onUpdate @autoSet column first (server-owned); onCreate - // columns are never touched on update (createdAt is immutable). - for (field in onUpdateAutoSetFields) { - append(" it[${tableObjectName}.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}\n") - } - for (field in patchSettableFields) { - val fn = field.name - val cap = capitalizeFirst(fn) - val col = "$tableObjectName.$fn" - if (KotlinGenUtil.isRequiredField(field)) { - append(" if (has$cap) it[$col] = v$cap!!\n") - } else { - append(" if (has$cap) { if (null$cap) it[$col] = null else it[$col] = v$cap }\n") - } - } - append(" }\n") - append(" }\n") - // Close the "any present" guard only when it was opened (see mustStampOnUpdate above). - if (!mustStampOnUpdate) append(" }\n") - } else if (mustStampOnUpdate) { - // No caller-settable columns, but onUpdate @autoSet must still bump on every patch. - append(" ${tableObjectName}.update({ ${tableObjectName}.${pkFieldName} eq id }) {\n") - for (field in onUpdateAutoSetFields) { - append(" it[${tableObjectName}.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}\n") - } - append(" }\n") } - // #214: read the (possibly-updated) row back through the READ object so the response - // carries the derived fields; the write above targeted the write table. - append(" val row = ${readObj}.selectAll().where { ${readObj}.${pkFieldName} eq id }.singleOrNull()\n") - append(" if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" else ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)\n") - append(" }\n\n") - - // DELETE — Exposed's `deleteWhere` is an extension fn on Table; the import - // above pulls it in. 204 No Content on success, 404 envelope on miss. - // The `eq` op must be resolved through SqlExpressionBuilder: deleteWhere's - // lambda receiver does NOT bring the comparison ops into scope on its own - // (unlike `selectAll().where { }`), so a bare `Table.id eq id` is an - // "Unresolved reference: eq" compile error. (Surfaced by the SP-F - // generated-controller HTTP lane; mirrors the hand-rolled reference server.) - append(" @DeleteMapping(\"/{id}\")\n") - append(" fun delete(@PathVariable id: $pkParamType): ResponseEntity = transaction {\n") - if (api == ExposedApi.V1) { - // issue #390: `eq` is a plain top-level import under 1.x — deleteWhere's lambda - // takes the table as an ordinary (unused) parameter, not an implicit receiver, so - // the `with(SqlExpressionBuilder)` wrapper 0.x needed is both unavailable and - // unnecessary (bare top-level `eq` resolves regardless of lambda receiver). - append(" val deleted = ${tableObjectName}.deleteWhere { ${tableObjectName}.${pkFieldName} eq id }\n") - } else { - append(" val deleted = ${tableObjectName}.deleteWhere { with(SqlExpressionBuilder) { ${tableObjectName}.${pkFieldName} eq id } }\n") + // Every issue found above is answered at once, before anything is written. + w.line("if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)") + // Apply the already-bound + validated values. Columns are qualified (`Table.col`) + // so a field named like the `body`/`id` params can't shadow them. + w.open("${tableObjectName}.update({ ${tableObjectName}.${pkFieldName} eq id }) {") + // #203/ADR-0045: bump every onUpdate @autoSet column first (server-owned); onCreate + // columns are never touched on update (createdAt is immutable). + for (field in onUpdateAutoSetFields) { + w.line("it[${tableObjectName}.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}") } - append(" if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" else ResponseEntity.noContent().build()\n") - append(" }\n") - - // FR-018 M:N traversal — GET /{id}/ exposes each - // @cardinality:"many" + @through relationship as a sub-resource of the source, - // returning the related target rows. The source URL segment is the entity name - // pluralized (handled by @RequestMapping above; getShortName() drives the - // segment, NOT the physical @table); the relation segment is the relationship - // name. Related-row order is not contractual. The traversal delegates to the - // Table.Query(id) Exposed join helper emitted by - // KotlinRelationsGenerator (hetero / directed self-join / symmetric union-on-read, - // junction FK fields derived via the cross-port M2MFields SSOT). - for (nav in m2mNavs) { - emitM2mEndpoint(this, pkg, shortName, nav, pkParamType) + for (field in patchSettableFields) { + val fn = field.name + val cap = capitalizeFirst(fn) + val col = "$tableObjectName.$fn" + if (KotlinGenUtil.isRequiredField(field)) { + w.line("if (has$cap) it[$col] = v$cap!!") + } else { + w.line("if (has$cap) { if (null$cap) it[$col] = null else it[$col] = v$cap }") + } } - - appendConstraintHandler() - append("}\n") + w.close("}") + w.close("}") + // Close the "any present" guard only when it was opened (see mustStampOnUpdate above). + if (!mustStampOnUpdate) w.close("}") + } else if (mustStampOnUpdate) { + // No caller-settable columns, but onUpdate @autoSet must still bump on every patch. + w.open("${tableObjectName}.update({ ${tableObjectName}.${pkFieldName} eq id }) {") + for (field in onUpdateAutoSetFields) { + w.line("it[${tableObjectName}.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}") + } + w.close("}") } + // #214: read the (possibly-updated) row back through the READ object so the response + // carries the derived fields; the write above targeted the write table. + w.line("val row = ${readObj}.selectAll().where { ${readObj}.${pkFieldName} eq id }.singleOrNull()") + w.line("if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") + w.line("else ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)") + w.close("}").blank() + + // DELETE — Exposed's `deleteWhere` is an extension fn on Table; the import + // above pulls it in. 204 No Content on success, 404 envelope on miss. + // The `eq` op must be resolved through SqlExpressionBuilder: deleteWhere's + // lambda receiver does NOT bring the comparison ops into scope on its own + // (unlike `selectAll().where { }`), so a bare `Table.id eq id` is an + // "Unresolved reference: eq" compile error. (Surfaced by the SP-F + // generated-controller HTTP lane; mirrors the hand-rolled reference server.) + w.line("@DeleteMapping(\"/{id}\")") + w.open("fun delete(@PathVariable id: $pkParamType): ResponseEntity = transaction {") + if (api == ExposedApi.V1) { + // issue #390: `eq` is a plain top-level import under 1.x — deleteWhere's lambda + // takes the table as an ordinary (unused) parameter, not an implicit receiver, so + // the `with(SqlExpressionBuilder)` wrapper 0.x needed is both unavailable and + // unnecessary (bare top-level `eq` resolves regardless of lambda receiver). + w.line("val deleted = ${tableObjectName}.deleteWhere { ${tableObjectName}.${pkFieldName} eq id }") + } else { + w.line("val deleted = ${tableObjectName}.deleteWhere { with(SqlExpressionBuilder) { ${tableObjectName}.${pkFieldName} eq id } }") + } + w.line("if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") + w.line("else ResponseEntity.noContent().build()") + w.close("}") + + // FR-018 M:N traversal — GET /{id}/ exposes each + // @cardinality:"many" + @through relationship as a sub-resource of the source, + // returning the related target rows. The source URL segment is the entity name + // pluralized (handled by @RequestMapping above; getShortName() drives the + // segment, NOT the physical @table); the relation segment is the relationship + // name. Related-row order is not contractual. The traversal delegates to the + // Table.Query(id) Exposed join helper emitted by + // KotlinRelationsGenerator (hetero / directed self-join / symmetric union-on-read, + // junction FK fields derived via the cross-port M2MFields SSOT). + for (nav in m2mNavs) { + emitM2mEndpoint(w, pkg, shortName, nav, pkParamType) + } + + appendConstraintHandler(w) + w.close("}") + val source = w.toString() val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("${shortName}Controller.kt") GeneratedFileWriter.write(outFile, source) @@ -1008,428 +1002,428 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase navs.any { it.targetCredentialFields.isNotEmpty() } } val needsMapper = anyPatchFields || rejectUnknown || strips - val src = buildString { - if (pkg.isNotEmpty()) append("package $pkg\n\n") - append("import ${ExposedImports.core(api, "Op")}\n") - append("import ${ExposedImports.core(api, "ResultRow")}\n") - append("import ${ExposedImports.core(api, "SortOrder")}\n") - // issue #390 (review fix): see emit()'s identical comment above — same scoping, - // against this TPH base's filterSpecs (the union of its own + every subtype's - // scalar columns) rather than a single entity's scalarFields. - if (api == ExposedApi.V1) { - for (op in v1FilterOperatorImports(filterSpecs)) append("import ${ExposedImports.core(api, op)}\n") - } else { - append("import org.jetbrains.exposed.sql.SqlExpressionBuilder\n") - } - append("import ${ExposedImports.core(api, "and")}\n") - append("import ${ExposedImports.jdbc(api, "deleteWhere")}\n") - append("import ${ExposedImports.jdbc(api, "insert")}\n") - append("import ${ExposedImports.jdbc(api, "selectAll")}\n") - append("import ${ExposedImports.jdbc(api, "update")}\n") - append("import ${ExposedImports.transactions(api, "transaction")}\n") - // FR-035 present-key PATCH: the per-subtype update handler binds the RAW JsonNode (not the - // union data class, which cannot see absent-vs-null) so the tristate (omitted / present-null - // / present-value) is visible. - append("import com.fasterxml.jackson.databind.JsonNode\n") - // FR-036: each present PATCH value binds via the Spring-configured ObjectMapper and is - // validated through a jakarta Validator — imported only when at least one subtype has a - // settable column (an unused import/ctor param would fail the module's allWarningsAsErrors - // compile). - if (anyPatchFields) { - append("import com.fasterxml.jackson.core.type.TypeReference\n") - append("import com.fasterxml.jackson.databind.ObjectMapper\n") - append("import jakarta.validation.Validator\n") - } else if (needsMapper) { - append("import com.fasterxml.jackson.databind.ObjectMapper\n") - } - append("import org.springframework.http.HttpStatus\n") - append("import org.springframework.http.ResponseEntity\n") - append("import org.springframework.web.bind.annotation.DeleteMapping\n") - append("import org.springframework.web.bind.annotation.ExceptionHandler\n") - append("import org.springframework.web.bind.annotation.GetMapping\n") - append("import org.springframework.web.bind.annotation.PathVariable\n") - append("import org.springframework.web.bind.annotation.PostMapping\n") - append("import org.springframework.web.bind.annotation.RequestBody\n") - append("import org.springframework.web.bind.annotation.RequestMapping\n") - append("import org.springframework.web.bind.annotation.RequestMethod\n") - append("import org.springframework.web.bind.annotation.RequestParam\n") - append("import org.springframework.web.bind.annotation.RestController\n") - // FR-009 filter pipeline support (mirrors the vanilla controller's import set). - append("import jakarta.servlet.http.HttpServletRequest\n") - append("import java.io.ByteArrayOutputStream\n") - append("import java.nio.charset.StandardCharsets\n") - append("import java.sql.Timestamp\n") - // ADR-0036 Wave 2: import java.time.Instant only when a default field.timestamp - // column (→ Instant) is in the filter surface — keeps Instant-free entities - // byte-identical. - if (filterSpecs.any { it.elementType == "Instant" }) { - append("import java.time.Instant\n") - } - // A uuid PK / uuid union column surfaces java.util.UUID in the by-id route - // signatures and the filter-dispatch casts — same conditional import as the - // vanilla controller, so uuid-free hierarchies stay byte-identical. - if (pkParamType == "UUID" || filterSpecs.any { it.elementType == "UUID" }) { - append("import java.util.UUID\n") - } - // See emit()'s identical BigDecimal/URI/InetAddress comments above: a filterable decimal - // column casts `p.value as BigDecimal`, so the import is needed here too. - if (filterSpecs.any { it.elementType == "BigDecimal" }) { - append("import java.math.BigDecimal\n") - } - if (filterSpecs.any { it.elementType == "URI" }) { - append("import java.net.URI\n") - } - if (filterSpecs.any { it.elementType == "InetAddress" }) { - append("import java.net.InetAddress\n") - } - if (filterSpecs.any { it.elementType == "Duration" }) { - append("import java.time.Duration\n") - } - // FR-009 (#179): a filterable enum in the union — the discriminator included — is - // compared as its stored string via `col.castTo(TextColumnType())`; same - // conditional imports as the vanilla controller. - if (filterSpecs.any { needsStringCastDispatch(it.subType, it.elementType, it.intBackedEnumType) }) { - append("import ${ExposedImports.core(api, "TextColumnType")}\n") - append("import ${ExposedImports.core(api, "castTo")}\n") + val w = KotlinWriter().packageName(pkg) + w.use(ExposedImports.core(api, "Op")) + w.use(ExposedImports.core(api, "ResultRow")) + w.use(ExposedImports.core(api, "SortOrder")) + // issue #390 (review fix): see emit()'s identical comment above — same scoping, + // against this TPH base's filterSpecs (the union of its own + every subtype's + // scalar columns) rather than a single entity's scalarFields. + if (api == ExposedApi.V1) { + for (op in v1FilterOperatorImports(filterSpecs)) w.use(ExposedImports.core(api, op)) + } else { + w.use("org.jetbrains.exposed.sql.SqlExpressionBuilder") + } + w.use(ExposedImports.core(api, "and")) + w.use(ExposedImports.jdbc(api, "deleteWhere")) + w.use(ExposedImports.jdbc(api, "insert")) + w.use(ExposedImports.jdbc(api, "selectAll")) + w.use(ExposedImports.jdbc(api, "update")) + w.use(ExposedImports.transactions(api, "transaction")) + // FR-035 present-key PATCH: the per-subtype update handler binds the RAW JsonNode (not the + // union data class, which cannot see absent-vs-null) so the tristate (omitted / present-null + // / present-value) is visible. + w.use("com.fasterxml.jackson.databind.JsonNode") + // FR-036: each present PATCH value binds via the Spring-configured ObjectMapper and is + // validated through a jakarta Validator — imported only when at least one subtype has a + // settable column (an unused import/ctor param would fail the module's allWarningsAsErrors + // compile). + if (anyPatchFields) { + w.use("com.fasterxml.jackson.core.type.TypeReference") + w.use("com.fasterxml.jackson.databind.ObjectMapper") + w.use("jakarta.validation.Validator") + } else if (needsMapper) { + w.use("com.fasterxml.jackson.databind.ObjectMapper") + } + w.use("org.springframework.http.HttpStatus") + w.use("org.springframework.http.ResponseEntity") + w.use("org.springframework.web.bind.annotation.DeleteMapping") + w.use("org.springframework.web.bind.annotation.ExceptionHandler") + w.use("org.springframework.web.bind.annotation.GetMapping") + w.use("org.springframework.web.bind.annotation.PathVariable") + w.use("org.springframework.web.bind.annotation.PostMapping") + w.use("org.springframework.web.bind.annotation.RequestBody") + w.use("org.springframework.web.bind.annotation.RequestMapping") + w.use("org.springframework.web.bind.annotation.RequestMethod") + w.use("org.springframework.web.bind.annotation.RequestParam") + w.use("org.springframework.web.bind.annotation.RestController") + // FR-009 filter pipeline support (mirrors the vanilla controller's import set). + w.use("jakarta.servlet.http.HttpServletRequest") + w.use("java.io.ByteArrayOutputStream") + w.use("java.nio.charset.StandardCharsets") + w.use("java.sql.Timestamp") + // ADR-0036 Wave 2: import java.time.Instant only when a default field.timestamp + // column (→ Instant) is in the filter surface — keeps Instant-free entities + // byte-identical. + if (filterSpecs.any { it.elementType == "Instant" }) { + w.use("java.time.Instant") + } + // A uuid PK / uuid union column surfaces java.util.UUID in the by-id route + // signatures and the filter-dispatch casts — same conditional import as the + // vanilla controller, so uuid-free hierarchies stay byte-identical. + if (pkParamType == "UUID" || filterSpecs.any { it.elementType == "UUID" }) { + w.use("java.util.UUID") + } + // See emit()'s identical BigDecimal/URI/InetAddress comments above: a filterable decimal + // column casts `p.value as BigDecimal`, so the import is needed here too. + if (filterSpecs.any { it.elementType == "BigDecimal" }) { + w.use("java.math.BigDecimal") + } + if (filterSpecs.any { it.elementType == "URI" }) { + w.use("java.net.URI") + } + if (filterSpecs.any { it.elementType == "InetAddress" }) { + w.use("java.net.InetAddress") + } + if (filterSpecs.any { it.elementType == "Duration" }) { + w.use("java.time.Duration") + } + // FR-009 (#179): a filterable enum in the union — the discriminator included — is + // compared as its stored string via `col.castTo(TextColumnType())`; same + // conditional imports as the vanilla controller. + if (filterSpecs.any { needsStringCastDispatch(it.subType, it.elementType, it.intBackedEnumType) }) { + w.use(ExposedImports.core(api, "TextColumnType")) + w.use(ExposedImports.core(api, "castTo")) + } + w.use("java.time.LocalDate") + w.use("java.time.LocalDateTime") + w.use("java.time.LocalTime") + w.use("java.time.format.DateTimeFormatter") + val tphNavs = baseM2mNavs + plan.subtypes.flatMap { subtypeM2mNavs(it) } + for (line in KotlinM2mSupport.importLines(tphNavs, pkg, junction = false, dataClass = true)) { + w.use("$line") + } + w.blank() + + // sort allowlist (base scalar columns — the polymorphic sort surface) + w.line("/** GENERATED — sort allowlist for $shortName (cross-port API contract). */") + w.open("private val ${shortName}SortAllowlist = setOf(") + for (f in sortFields) w.line("\"$f\",") + w.close(")").blank() + // The polymorphic sort surface is the BASE's own columns, so the declared + // orders are read off the base too — same owner the allowlist came from. + appendSortDefaultOrders(w, shortName, base, sortFields) + // A key declared by the base or by ANY subtype is known on every route: a sibling subtype's column is + // dropped on another subtype's route, never refused. + appendKnownFields(w, shortName, base.metaFields.map { it.name } + plan.subtypes.flatMap { st -> st.entity.metaFields.map { it.name } }) + w.open("private fun parse${shortName}Sort(raw: String): Pair? {") + w.line("val parts = raw.split(\":\", limit = 2)") + w.line("val field = parts.getOrNull(0) ?: return null") + w.line("if (field !in ${shortName}SortAllowlist) return null") + // The `when` subject continues on the next line; the arms sit at that line's depth. + w.open("val dir = when (parts.getOrNull(1)?.lowercase()") + w.line("?: ${shortName}SortDefaultOrder[field] ?: \"asc\") {") + w.line("\"asc\" -> SortOrder.ASC_NULLS_LAST") + w.line("\"desc\" -> SortOrder.DESC_NULLS_FIRST") + w.line("else -> return null") + w.close("}") + w.line("return field to dir") + w.close("}").blank() + + // FR-009 filter pipeline over the UNION columns (parse + per-field Exposed Op dispatch), + // shared by the polymorphic + per-subtype list handlers — matches the Python/TS TPH lanes. + emitFilterPipeline(w, shortName, table, allowlistName, filterSpecs) + + // rowTo: union ResultRow → data class + w.line("/** GENERATED — map an Exposed ResultRow to the union $shortName data class. */") + w.open("private fun rowTo${shortName}(row: ResultRow): $shortName = $shortName(") + for (field in scalarFields) w.line("${field.name} = row[$table.${field.name}],") + w.close(")").blank() + appendRedactor(w, shortName, creds, strips) + + w.line("/**") + w.line(" * GENERATED — TPH discriminator-base controller for $shortName (polymorphic + per-subtype CRUD).") + w.line(" *") + // No `/**` glob in the example: Kotlin NESTS block comments (see emit()). + w.line(" * Auth: these endpoints are unauthenticated. In your Spring Security config, require") + w.line(" * authentication for `$routeBase` and every path under it (`requestMatchers` + `authenticated()`).") + w.line(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path") + w.line(" * config — eject this generator with `mvn metaobjects:eject` and hand-write those endpoints.") + w.line(" */") + w.line("@RestController") + w.line("@RequestMapping(\"$routeBase\")") + // FR-036: the per-subtype PATCH tristate binds present values through the Spring-configured + // ObjectMapper and validates them via the jakarta Validator — both injected only when a + // subtype has a settable column (else a no-arg controller, keeping unused params out). + if (anyPatchFields) { + w.open("class ${shortName}Controller(private val objectMapper: ObjectMapper, private val validator: Validator) {").blank() + } else if (needsMapper) { + w.open("class ${shortName}Controller(private val objectMapper: ObjectMapper) {").blank() + } else { + w.open("class ${shortName}Controller {").blank() + } + + // polymorphic list + w.line("@GetMapping") + w.open("fun list(") + w.line("@RequestParam(required = false) limit: Int?,") + w.line("@RequestParam(required = false) offset: Int?,") + w.line("@RequestParam(required = false) sort: String?,") + w.line("@RequestParam(required = false, name = \"withCount\") withCount: Int?,") + w.line("request: HttpServletRequest,") + w.reopen("): ResponseEntity = transaction {") + appendLimitGuard(w) + w.line("val filterResult = parse${shortName}Filter(request.queryString)") + w.line("if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)") + w.line("val whereOp = ${shortName}WhereOp(filterResult.predicates)") + w.line("var q = if (whereOp != null) $table.selectAll().where { whereOp } else $table.selectAll()") + w.open("if (sort != null) {") + w.line("val parsed = parse${shortName}Sort(sort)") + w.indented { w.line("?: return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)") } + w.line("val (field, dir) = parsed") + writeOrderBy(w, table, shortName, sortFields, exposedApi()) + w.close("}") + w.line("val total: Long = if (withCount == 1) q.count() else -1L") + // issue #390: Exposed 1.x's Query.limit(count) dropped the 0.x 2-arg + // limit(count, offset) overload — offset is now its OWN chained call. + if (api == ExposedApi.V1) { + w.line("val rows = q.limit(limit ?: ${defaultLimit()}).offset((offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }") + } else { + w.line("val rows = q.limit(limit ?: ${defaultLimit()}, (offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }") + } + w.line("if (withCount == 1) ResponseEntity.ok(mapOf(\"rows\" to rows, \"total\" to total) as Any)") + w.line("else ResponseEntity.ok(rows as Any)") + w.close("}").blank() + + // polymorphic get + w.line("@GetMapping(\"/{id}\")") + w.open("fun get(@PathVariable id: $pkParamType): ResponseEntity = transaction {") + w.line("val row = $table.selectAll().where { $table.$pkFieldName eq id }.singleOrNull()") + w.indented { w.line("?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") } + w.line("ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)") + w.close("}").blank() + + // Base-declared M:N — unscoped, same shape emitM2mEndpoint gives a vanilla entity. + for (nav in baseM2mNavs) { + emitM2mEndpoint(w, pkg, shortName, nav, pkParamType, m2mHelperNames.getValue(nav)) + } + + for (st in plan.subtypes) { + val seg = st.routeSegment + val disc = "$discEnum.${st.value}" // e.g. AuthType.Bridge + val sfx = capitalizeFirst(st.value) // method-name suffix, e.g. Bridge + // FR-036: the annotated Validation shape (emitted by KotlinEntityGenerator) that + // the per-subtype POST + PATCH validate present values against — the bound union base + // data class is annotation-free. Referenced FQN-qualified when the subtype lives in a + // different package (this hand-rolled builder owns no import machinery, like emitM2m*), + // else bare. + val (stPkg, stShort) = PackageMapping.splitFqn(st.entity.name) + val validationRef = KotlinNaming.tphSubtypeValidationName(stShort).let { cls -> + if (stPkg == pkg || stPkg.isEmpty()) cls else "$stPkg.$cls" } - append("import java.time.LocalDate\n") - append("import java.time.LocalDateTime\n") - append("import java.time.LocalTime\n") - append("import java.time.format.DateTimeFormatter\n") - val tphNavs = baseM2mNavs + plan.subtypes.flatMap { subtypeM2mNavs(it) } - for (line in KotlinM2mSupport.importLines(tphNavs, pkg, junction = false, dataClass = true)) { - append("import $line\n") + // The subtype's settable columns (SSOT shared with the Validation shape) — the + // create body + present PATCH values are both validated against exactly this set. + val stPatch = subtypePatchFields(st) + + w.line("// --- subtype ${st.value} (segment /$seg) ---") + + // per-subtype list (discriminator scope AND'd with the FR-009 filter) + w.line("@GetMapping(\"/$seg\")") + w.open("fun list$sfx(") + w.line("@RequestParam(required = false) limit: Int?,") + w.line("@RequestParam(required = false) offset: Int?,") + w.line("@RequestParam(required = false) sort: String?,") + w.line("request: HttpServletRequest,") + w.reopen("): ResponseEntity = transaction {") + appendLimitGuard(w) + w.line("val filterResult = parse${shortName}Filter(request.queryString)") + w.line("if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)") + w.line("val whereOp = ${shortName}WhereOp(filterResult.predicates)") + w.open("var q = $table.selectAll().where {") + w.line("val d = $table.${plan.discriminatorField} eq $disc") + w.line("if (whereOp != null) d and whereOp else d") + w.close("}") + w.open("if (sort != null) {") + w.line("val parsed = parse${shortName}Sort(sort)") + w.indented { w.line("?: return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)") } + w.line("val (field, dir) = parsed") + writeOrderBy(w, table, shortName, sortFields, exposedApi()) + w.close("}") + // issue #390: Exposed 1.x's Query.limit(count) dropped the 0.x 2-arg + // limit(count, offset) overload — offset is now its OWN chained call. + if (api == ExposedApi.V1) { + w.line("val rows = q.limit(limit ?: ${defaultLimit()}).offset((offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }") + } else { + w.line("val rows = q.limit(limit ?: ${defaultLimit()}, (offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }") + } + w.line("ResponseEntity.ok(rows as Any)") + w.close("}").blank() + + // per-subtype get + w.line("@GetMapping(\"/$seg/{id}\")") + w.open("fun get$sfx(@PathVariable id: $pkParamType): ResponseEntity = transaction {") + w.line("val row = $table.selectAll().where { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }.singleOrNull()") + w.indented { w.line("?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") } + w.line("ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)") + w.close("}").blank() + + // per-subtype create (discriminator injected from URL). FR-036: validate each body + // value against the subtype's ANNOTATED Validation constraints BEFORE persisting, + // 400ing with the cross-port {"error":"validation"} envelope on any violation (an + // over-@maxLength or missing-@required column is a 400, not a silent 201). The bound + // body stays the union base data class (the shape the insert consumes), but the union is + // annotation-free — so validation runs PER FIELD against Validation, the SAME + // annotated shape + field set the per-subtype PATCH validates. validateValue applies + // @NotNull to a null value, so an absent @required column 400s too — mirroring the + // vanilla create's whole-bean validate, scoped to this subtype. + // The subtype's cross-field rules live on its own data class as class-level @AssertTrue + // properties, which the per-property validateValue below never reaches. They are + // evaluated here against the bound union body, the discriminator read as this route's + // pinned value. + val crossFieldRules = KotlinCrossFieldRules.rules(st.entity) { + if (it.name == plan.discriminatorField) disc else "dto.${it.name}" } - append("\n") - - // sort allowlist (base scalar columns — the polymorphic sort surface) - append("/** GENERATED — sort allowlist for $shortName (cross-port API contract). */\n") - append("private val ${shortName}SortAllowlist = setOf(\n") - for (f in sortFields) append(" \"$f\",\n") - append(")\n\n") - // The polymorphic sort surface is the BASE's own columns, so the declared - // orders are read off the base too — same owner the allowlist came from. - appendSortDefaultOrders(this, shortName, base, sortFields) - // A key declared by the base or by ANY subtype is known on every route: a sibling subtype's column is - // dropped on another subtype's route, never refused. - appendKnownFields(shortName, base.metaFields.map { it.name } + plan.subtypes.flatMap { st -> st.entity.metaFields.map { it.name } }) - append("private fun parse${shortName}Sort(raw: String): Pair? {\n") - append(" val parts = raw.split(\":\", limit = 2)\n") - append(" val field = parts.getOrNull(0) ?: return null\n") - append(" if (field !in ${shortName}SortAllowlist) return null\n") - append(" val dir = when (parts.getOrNull(1)?.lowercase()\n") - append(" ?: ${shortName}SortDefaultOrder[field] ?: \"asc\") {\n") - append(" \"asc\" -> SortOrder.ASC_NULLS_LAST\n") - append(" \"desc\" -> SortOrder.DESC_NULLS_FIRST\n") - append(" else -> return null\n") - append(" }\n") - append(" return field to dir\n") - append("}\n\n") - - // FR-009 filter pipeline over the UNION columns (parse + per-field Exposed Op dispatch), - // shared by the polymorphic + per-subtype list handlers — matches the Python/TS TPH lanes. - emitFilterPipeline(this, shortName, table, allowlistName, filterSpecs) - - // rowTo: union ResultRow → data class - append("/** GENERATED — map an Exposed ResultRow to the union $shortName data class. */\n") - append("private fun rowTo${shortName}(row: ResultRow): $shortName = $shortName(\n") - for (field in scalarFields) append(" ${field.name} = row[$table.${field.name}],\n") - append(")\n\n") - appendRedactor(this, shortName, creds, strips) - - append("/**\n") - append(" * GENERATED — TPH discriminator-base controller for $shortName (polymorphic + per-subtype CRUD).\n") - append(" *\n") - // No `/**` glob in the example: Kotlin NESTS block comments (see emit()). - append(" * Auth: these endpoints are unauthenticated. In your Spring Security config, require\n") - append(" * authentication for `$routeBase` and every path under it (`requestMatchers` + `authenticated()`).\n") - append(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path\n") - append(" * config — eject this generator with `mvn metaobjects:eject` and hand-write those endpoints.\n") - append(" */\n") - append("@RestController\n") - append("@RequestMapping(\"$routeBase\")\n") - // FR-036: the per-subtype PATCH tristate binds present values through the Spring-configured - // ObjectMapper and validates them via the jakarta Validator — both injected only when a - // subtype has a settable column (else a no-arg controller, keeping unused params out). - if (anyPatchFields) { - append("class ${shortName}Controller(private val objectMapper: ObjectMapper, private val validator: Validator) {\n\n") - } else if (needsMapper) { - append("class ${shortName}Controller(private val objectMapper: ObjectMapper) {\n\n") + if (crossFieldRules.isNotEmpty()) w.line("@Suppress(\"UNCHECKED_CAST\")") + w.line("@PostMapping(\"/$seg\")") + if (rejectUnknown) { + // The raw body is read first so an undeclared key is refused whatever the host's ObjectMapper does. + w.open("fun create$sfx(@RequestBody body: JsonNode): ResponseEntity = transaction {") + w.line("if (!body.isObject) return@transaction ResponseEntity.badRequest().body(MetaValidationIssues.Collector().add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)") + appendUnknownGuard(w, shortName) + w.open("val dto: $shortName = try {") + w.line("objectMapper.treeToValue(body, ${shortName}::class.java)") + w.reopen("} catch (e: Exception) {") + w.line("return@transaction ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any)") + w.close("}") } else { - append("class ${shortName}Controller {\n\n") + w.open("fun create$sfx(@RequestBody dto: $shortName): ResponseEntity = transaction {") } - - // polymorphic list - append(" @GetMapping\n") - append(" fun list(\n") - append(" @RequestParam(required = false) limit: Int?,\n") - append(" @RequestParam(required = false) offset: Int?,\n") - append(" @RequestParam(required = false) sort: String?,\n") - append(" @RequestParam(required = false, name = \"withCount\") withCount: Int?,\n") - append(" request: HttpServletRequest,\n") - append(" ): ResponseEntity = transaction {\n") - appendLimitGuard() - append(" val filterResult = parse${shortName}Filter(request.queryString)\n") - append(" if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)\n") - append(" val whereOp = ${shortName}WhereOp(filterResult.predicates)\n") - append(" var q = if (whereOp != null) $table.selectAll().where { whereOp } else $table.selectAll()\n") - append(" if (sort != null) {\n") - append(" val parsed = parse${shortName}Sort(sort)\n") - append(" ?: return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)\n") - append(" val (field, dir) = parsed\n") - append(" q = q.orderBy(${sortColumnExpr(table, shortName, sortFields, exposedApi())} to dir)\n") - append(" }\n") - append(" val total: Long = if (withCount == 1) q.count() else -1L\n") - // issue #390: Exposed 1.x's Query.limit(count) dropped the 0.x 2-arg - // limit(count, offset) overload — offset is now its OWN chained call. - if (api == ExposedApi.V1) { - append(" val rows = q.limit(limit ?: ${defaultLimit()}).offset((offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }\n") - } else { - append(" val rows = q.limit(limit ?: ${defaultLimit()}, (offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }\n") + w.line("val issues = MetaValidationIssues.Collector()") + for (field in stPatch) { + w.line("issues.addAt(validator.validateValue($validationRef::class.java, \"${field.name}\", dto.${field.name}), \"${field.name}\")") + appendDecimalRangeCheck(w, field, "dto.${field.name}") } - append(" if (withCount == 1) ResponseEntity.ok(mapOf(\"rows\" to rows, \"total\" to total) as Any)\n") - append(" else ResponseEntity.ok(rows as Any)\n") - append(" }\n\n") - - // polymorphic get - append(" @GetMapping(\"/{id}\")\n") - append(" fun get(@PathVariable id: $pkParamType): ResponseEntity = transaction {\n") - append(" val row = $table.selectAll().where { $table.$pkFieldName eq id }.singleOrNull()\n") - append(" ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)\n") - append(" }\n\n") - - // Base-declared M:N — unscoped, same shape emitM2mEndpoint gives a vanilla entity. - for (nav in baseM2mNavs) { - emitM2mEndpoint(this, pkg, shortName, nav, pkParamType, m2mHelperNames.getValue(nav)) + for ((_, rule) in crossFieldRules) { + w.line("if (!($rule)) issues.add(\"custom\", emptyList(), \"a cross-field rule failed\")") } - - for (st in plan.subtypes) { - val seg = st.routeSegment - val disc = "$discEnum.${st.value}" // e.g. AuthType.Bridge - val sfx = capitalizeFirst(st.value) // method-name suffix, e.g. Bridge - // FR-036: the annotated Validation shape (emitted by KotlinEntityGenerator) that - // the per-subtype POST + PATCH validate present values against — the bound union base - // data class is annotation-free. Referenced FQN-qualified when the subtype lives in a - // different package (this hand-rolled builder owns no import machinery, like emitM2m*), - // else bare. - val (stPkg, stShort) = PackageMapping.splitFqn(st.entity.name) - val validationRef = KotlinNaming.tphSubtypeValidationName(stShort).let { cls -> - if (stPkg == pkg || stPkg.isEmpty()) cls else "$stPkg.$cls" - } - // The subtype's settable columns (SSOT shared with the Validation shape) — the - // create body + present PATCH values are both validated against exactly this set. - val stPatch = subtypePatchFields(st) - - append(" // --- subtype ${st.value} (segment /$seg) ---\n") - - // per-subtype list (discriminator scope AND'd with the FR-009 filter) - append(" @GetMapping(\"/$seg\")\n") - append(" fun list$sfx(\n") - append(" @RequestParam(required = false) limit: Int?,\n") - append(" @RequestParam(required = false) offset: Int?,\n") - append(" @RequestParam(required = false) sort: String?,\n") - append(" request: HttpServletRequest,\n") - append(" ): ResponseEntity = transaction {\n") - appendLimitGuard() - append(" val filterResult = parse${shortName}Filter(request.queryString)\n") - append(" if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)\n") - append(" val whereOp = ${shortName}WhereOp(filterResult.predicates)\n") - append(" var q = $table.selectAll().where {\n") - append(" val d = $table.${plan.discriminatorField} eq $disc\n") - append(" if (whereOp != null) d and whereOp else d\n") - append(" }\n") - append(" if (sort != null) {\n") - append(" val parsed = parse${shortName}Sort(sort)\n") - append(" ?: return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)\n") - append(" val (field, dir) = parsed\n") - append(" q = q.orderBy(${sortColumnExpr(table, shortName, sortFields, exposedApi())} to dir)\n") - append(" }\n") - // issue #390: Exposed 1.x's Query.limit(count) dropped the 0.x 2-arg - // limit(count, offset) overload — offset is now its OWN chained call. - if (api == ExposedApi.V1) { - append(" val rows = q.limit(limit ?: ${defaultLimit()}).offset((offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }\n") - } else { - append(" val rows = q.limit(limit ?: ${defaultLimit()}, (offset ?: 0).toLong()).map { ${wireRow(shortName, creds, "it")} }\n") + w.line("if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)") + // #203/ADR-0045: capture one now() per temporal type so createdAt == updatedAt exactly. + for ((expr, valName) in insertNowVal) w.line("val $valName = $expr") + w.open("val newId = $table.insert {") + w.line("it[$table.${plan.discriminatorField}] = $disc") + // `@generation: uuid` key minted app-side — see the vanilla create. + if (uuidGeneratedPk(base, pkFieldName)) w.line("it[$table.$pkFieldName] = java.util.UUID.randomUUID()") + // Only what THIS route's subtype may set on create: its effective (base + own) + // columns, never a readOnly or derived one and never a sibling subtype's column. + val createNames = st.entity.metaFields + .filter { !KotlinGenUtil.isReadOnlyMutability(it) && !KotlinGenUtil.isDerivedField(it) } + .map { it.name }.toSet() + for (f in writableFields.filter { it in createNames }) { + // A column is non-null in the union table iff it is a BASE @required field + // (subtype-only columns are folded NULLABLE). For a non-null column the union + // DTO field is still nullable, so force non-null on create (create bodies for + // that subtype always supply it); nullable columns bind the nullable value as-is. + val colNonNull = baseFieldNames.contains(f) && KotlinGenUtil.isRequiredField(scalarFields.first { it.name == f }) + if (colNonNull) w.line("it[$table.$f] = dto.$f!!") + else w.line("it[$table.$f] = dto.$f") } - append(" ResponseEntity.ok(rows as Any)\n") - append(" }\n\n") - - // per-subtype get - append(" @GetMapping(\"/$seg/{id}\")\n") - append(" fun get$sfx(@PathVariable id: $pkParamType): ResponseEntity = transaction {\n") - append(" val row = $table.selectAll().where { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }.singleOrNull()\n") - append(" ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)\n") - append(" }\n\n") - - // per-subtype create (discriminator injected from URL). FR-036: validate each body - // value against the subtype's ANNOTATED Validation constraints BEFORE persisting, - // 400ing with the cross-port {"error":"validation"} envelope on any violation (an - // over-@maxLength or missing-@required column is a 400, not a silent 201). The bound - // body stays the union base data class (the shape the insert consumes), but the union is - // annotation-free — so validation runs PER FIELD against Validation, the SAME - // annotated shape + field set the per-subtype PATCH validates. validateValue applies - // @NotNull to a null value, so an absent @required column 400s too — mirroring the - // vanilla create's whole-bean validate, scoped to this subtype. - // The subtype's cross-field rules live on its own data class as class-level @AssertTrue - // properties, which the per-property validateValue below never reaches. They are - // evaluated here against the bound union body, the discriminator read as this route's - // pinned value. - val crossFieldRules = KotlinCrossFieldRules.rules(st.entity) { - if (it.name == plan.discriminatorField) disc else "dto.${it.name}" - } - if (crossFieldRules.isNotEmpty()) append(" @Suppress(\"UNCHECKED_CAST\")\n") - append(" @PostMapping(\"/$seg\")\n") - if (rejectUnknown) { - // The raw body is read first so an undeclared key is refused whatever the host's ObjectMapper does. - append(" fun create$sfx(@RequestBody body: JsonNode): ResponseEntity = transaction {\n") - append(" if (!body.isObject) return@transaction ResponseEntity.badRequest().body(MetaValidationIssues.Collector().add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)\n") - appendUnknownGuard(shortName) - append(" val dto: $shortName = try {\n") - append(" objectMapper.treeToValue(body, ${shortName}::class.java)\n") - append(" } catch (e: Exception) {\n") - append(" return@transaction ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any)\n") - append(" }\n") - } else { - append(" fun create$sfx(@RequestBody dto: $shortName): ResponseEntity = transaction {\n") - } - append(" val issues = MetaValidationIssues.Collector()\n") + // #203/ADR-0045: insert stamps onCreate+onUpdate @autoSet columns from the captured + // now() (the caller's dto value is ignored — never bound). + for (f in insertAutoSetFields) { + w.line("it[$table.${f.name}] = ${insertNowVal[KotlinTypeMapper.nowExpr(f)]}") + } + w.close("}[$table.$pkFieldName]") + w.line("val saved = $table.selectAll().where { $table.$pkFieldName eq newId }.single()") + w.line("ResponseEntity.status(HttpStatus.CREATED).body(${wireRow(shortName, creds, "saved")} as Any)") + w.close("}").blank() + + // per-subtype update — FR-035/FR-036 present-key PATCH tristate (mirrors the vanilla + // update handler), scoped to THIS subtype's own effective columns; discriminator immutable; + // 404 cross-subtype via the discriminator-scoped read-back. Bind the RAW JsonNode so + // absent-vs-null is visible: a non-object body, or an explicit null on a @required column + // (base or subtype), is a 400; an explicit null on a nullable column CLEARS it; an omitted + // column is untouched; a present value binds through the ObjectMapper (same codecs as + // create) and its present non-null value is validated via the jakarta Validator against the + // subtype's ANNOTATED Validation shape (the folded union base data class is + // annotation-free — so an over-@maxLength present value is a 400, matching the vanilla + // path + the per-subtype create). Binding + validation run at the transaction-lambda top + // level (a qualified return@transaction cannot cross the non-inline Exposed update{} + // lambda). An empty effective patch skips the update{} (Exposed rejects an empty SET) — a + // no-op read-back. + w.line("@RequestMapping(value = [\"/$seg/{id}\"], method = [RequestMethod.PATCH, RequestMethod.PUT])") + w.open("fun update$sfx(@PathVariable id: $pkParamType, @RequestBody body: JsonNode): ResponseEntity = transaction {") + appendPatchHead(w, stPatch, shortName) + // #203/ADR-0045: mirrors the vanilla update handler's mustStampOnUpdate control flow — + // an onUpdate @autoSet column must bump on EVERY patch, so the "any present" guard is + // dropped when one exists (else the guard would keep a no-settable-field patch from + // bumping it); with no caller-settable columns at all, a standalone update{} still bumps. + val mustStampOnUpdate = onUpdateAutoSetFields.isNotEmpty() + if (stPatch.isNotEmpty()) { + val settableNamesList = stPatch.joinToString(", ") { "\"${it.name}\"" } + if (!mustStampOnUpdate) w.open("if (listOf($settableNamesList).any { body.has(it) }) {") + w.open("run {") for (field in stPatch) { - append(" issues.addAt(validator.validateValue($validationRef::class.java, \"${field.name}\", dto.${field.name}), \"${field.name}\")\n") - appendDecimalRangeCheck(" ", field, "dto.${field.name}") - } - for ((_, rule) in crossFieldRules) { - append(" if (!($rule)) issues.add(\"custom\", emptyList(), \"a cross-field rule failed\")\n") - } - append(" if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)\n") - // #203/ADR-0045: capture one now() per temporal type so createdAt == updatedAt exactly. - for ((expr, valName) in insertNowVal) append(" val $valName = $expr\n") - append(" val newId = $table.insert {\n") - append(" it[$table.${plan.discriminatorField}] = $disc\n") - // `@generation: uuid` key minted app-side — see the vanilla create. - if (uuidGeneratedPk(base, pkFieldName)) append(" it[$table.$pkFieldName] = java.util.UUID.randomUUID()\n") - // Only what THIS route's subtype may set on create: its effective (base + own) - // columns, never a readOnly or derived one and never a sibling subtype's column. - val createNames = st.entity.metaFields - .filter { !KotlinGenUtil.isReadOnlyMutability(it) && !KotlinGenUtil.isDerivedField(it) } - .map { it.name }.toSet() - for (f in writableFields.filter { it in createNames }) { - // A column is non-null in the union table iff it is a BASE @required field - // (subtype-only columns are folded NULLABLE). For a non-null column the union - // DTO field is still nullable, so force non-null on create (create bodies for - // that subtype always supply it); nullable columns bind the nullable value as-is. - val colNonNull = baseFieldNames.contains(f) && KotlinGenUtil.isRequiredField(scalarFields.first { it.name == f }) - if (colNonNull) append(" it[$table.$f] = dto.$f!!\n") - else append(" it[$table.$f] = dto.$f\n") + // The union column's element type — a field.enum's materialized enum class resolved + // with the BASE as owner (exactly as the union data class + table type the folded + // column), NOT the wire String — so the bound value matches Exposed's Column. + val elem = KotlinTypeMapper.enumTypeName(field, base, providedEnums) ?: KotlinTypeMapper.kotlinTypeName(field) + val ktType = if (field.isArrayType) "kotlin.collections.List<$elem>" else "$elem" + val fn = field.name + val cap = capitalizeFirst(fn) + appendPatchFieldBinding(w, field, ktType, patchBindExpr(field, fn, ktType), "$validationRef::class.java") } - // #203/ADR-0045: insert stamps onCreate+onUpdate @autoSet columns from the captured - // now() (the caller's dto value is ignored — never bound). - for (f in insertAutoSetFields) { - append(" it[$table.${f.name}] = ${insertNowVal[KotlinTypeMapper.nowExpr(f)]}\n") + w.line("if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)") + // Apply the already-bound + validated values, scoped to (pk eq id) and (disc eq value). + // Columns are qualified ($table.col) so a field named like the body/id params can't shadow. + w.open("$table.update({ ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }) {") + // #203/ADR-0045: bump every onUpdate @autoSet column first (server-owned); onCreate + // columns are never touched on update (createdAt is immutable). + for (field in onUpdateAutoSetFields) { + w.line("it[$table.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}") } - append(" }[$table.$pkFieldName]\n") - append(" val saved = $table.selectAll().where { $table.$pkFieldName eq newId }.single()\n") - append(" ResponseEntity.status(HttpStatus.CREATED).body(${wireRow(shortName, creds, "saved")} as Any)\n") - append(" }\n\n") - - // per-subtype update — FR-035/FR-036 present-key PATCH tristate (mirrors the vanilla - // update handler), scoped to THIS subtype's own effective columns; discriminator immutable; - // 404 cross-subtype via the discriminator-scoped read-back. Bind the RAW JsonNode so - // absent-vs-null is visible: a non-object body, or an explicit null on a @required column - // (base or subtype), is a 400; an explicit null on a nullable column CLEARS it; an omitted - // column is untouched; a present value binds through the ObjectMapper (same codecs as - // create) and its present non-null value is validated via the jakarta Validator against the - // subtype's ANNOTATED Validation shape (the folded union base data class is - // annotation-free — so an over-@maxLength present value is a 400, matching the vanilla - // path + the per-subtype create). Binding + validation run at the transaction-lambda top - // level (a qualified return@transaction cannot cross the non-inline Exposed update{} - // lambda). An empty effective patch skips the update{} (Exposed rejects an empty SET) — a - // no-op read-back. - append(" @RequestMapping(value = [\"/$seg/{id}\"], method = [RequestMethod.PATCH, RequestMethod.PUT])\n") - append(" fun update$sfx(@PathVariable id: $pkParamType, @RequestBody body: JsonNode): ResponseEntity = transaction {\n") - appendPatchHead(this, stPatch, shortName) - // #203/ADR-0045: mirrors the vanilla update handler's mustStampOnUpdate control flow — - // an onUpdate @autoSet column must bump on EVERY patch, so the "any present" guard is - // dropped when one exists (else the guard would keep a no-settable-field patch from - // bumping it); with no caller-settable columns at all, a standalone update{} still bumps. - val mustStampOnUpdate = onUpdateAutoSetFields.isNotEmpty() - if (stPatch.isNotEmpty()) { - val settableNamesList = stPatch.joinToString(", ") { "\"${it.name}\"" } - if (!mustStampOnUpdate) append(" if (listOf($settableNamesList).any { body.has(it) }) {\n") - append(" run {\n") - for (field in stPatch) { - // The union column's element type — a field.enum's materialized enum class resolved - // with the BASE as owner (exactly as the union data class + table type the folded - // column), NOT the wire String — so the bound value matches Exposed's Column. - val elem = KotlinTypeMapper.enumTypeName(field, base, providedEnums) ?: KotlinTypeMapper.kotlinTypeName(field) - val ktType = if (field.isArrayType) "kotlin.collections.List<$elem>" else "$elem" - val fn = field.name - val cap = capitalizeFirst(fn) - appendPatchFieldBinding(this, field, ktType, patchBindExpr(field, fn, ktType), "$validationRef::class.java") - } - append(" if (!issues.isEmpty()) return@transaction ResponseEntity.badRequest().body(issues.body() as Any)\n") - // Apply the already-bound + validated values, scoped to (pk eq id) and (disc eq value). - // Columns are qualified ($table.col) so a field named like the body/id params can't shadow. - append(" $table.update({ ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }) {\n") - // #203/ADR-0045: bump every onUpdate @autoSet column first (server-owned); onCreate - // columns are never touched on update (createdAt is immutable). - for (field in onUpdateAutoSetFields) { - append(" it[$table.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}\n") - } - for (field in stPatch) { - val fn = field.name - val cap = capitalizeFirst(fn) - val col = "$table.$fn" - if (KotlinGenUtil.isRequiredField(field)) { - append(" if (has$cap) it[$col] = v$cap!!\n") - } else { - append(" if (has$cap) { if (null$cap) it[$col] = null else it[$col] = v$cap }\n") - } - } - append(" }\n") - append(" }\n") - // Close the "any present" guard only when it was opened (see mustStampOnUpdate above). - if (!mustStampOnUpdate) append(" }\n") - } else if (mustStampOnUpdate) { - // No caller-settable columns for this subtype, but onUpdate @autoSet must still bump. - append(" $table.update({ ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }) {\n") - for (field in onUpdateAutoSetFields) { - append(" it[$table.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}\n") + for (field in stPatch) { + val fn = field.name + val cap = capitalizeFirst(fn) + val col = "$table.$fn" + if (KotlinGenUtil.isRequiredField(field)) { + w.line("if (has$cap) it[$col] = v$cap!!") + } else { + w.line("if (has$cap) { if (null$cap) it[$col] = null else it[$col] = v$cap }") } - append(" }\n") - } - append(" val row = $table.selectAll().where { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }.singleOrNull()\n") - append(" if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" else ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)\n") - append(" }\n\n") - - // per-subtype delete (404 cross-subtype) - append(" @DeleteMapping(\"/$seg/{id}\")\n") - append(" fun delete$sfx(@PathVariable id: $pkParamType): ResponseEntity = transaction {\n") - if (api == ExposedApi.V1) { - // issue #390 — see the vanilla controller's delete() for why V1 drops the - // `with(SqlExpressionBuilder)` wrapper (bare top-level eq/and resolve here). - append(" val deleted = $table.deleteWhere { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }\n") - } else { - append(" val deleted = $table.deleteWhere { with(SqlExpressionBuilder) { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) } }\n") } - append(" if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" else ResponseEntity.noContent().build()\n") - append(" }\n\n") - - // M:N traversal scoped to THIS subtype — every relationship it resolves, - // inherited ones (e.g. a base-declared relationship) included. - for (nav in subtypeM2mNavs(st)) { - emitTphSubtypeM2mEndpoint( - this, pkg, table, pkFieldName, plan.discriminatorField, disc, seg, sfx, nav, pkParamType, - m2mHelperNames.getValue(nav), - ) + w.close("}") + w.close("}") + // Close the "any present" guard only when it was opened (see mustStampOnUpdate above). + if (!mustStampOnUpdate) w.close("}") + } else if (mustStampOnUpdate) { + // No caller-settable columns for this subtype, but onUpdate @autoSet must still bump. + w.open("$table.update({ ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }) {") + for (field in onUpdateAutoSetFields) { + w.line("it[$table.${field.name}] = ${KotlinTypeMapper.nowExpr(field)}") } + w.close("}") + } + w.line("val row = $table.selectAll().where { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }.singleOrNull()") + w.line("if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") + w.line("else ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)") + w.close("}").blank() + + // per-subtype delete (404 cross-subtype) + w.line("@DeleteMapping(\"/$seg/{id}\")") + w.open("fun delete$sfx(@PathVariable id: $pkParamType): ResponseEntity = transaction {") + if (api == ExposedApi.V1) { + // issue #390 — see the vanilla controller's delete() for why V1 drops the + // `with(SqlExpressionBuilder)` wrapper (bare top-level eq/and resolve here). + w.line("val deleted = $table.deleteWhere { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) }") + } else { + w.line("val deleted = $table.deleteWhere { with(SqlExpressionBuilder) { ($table.$pkFieldName eq id) and ($table.${plan.discriminatorField} eq $disc) } }") + } + w.line("if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") + w.line("else ResponseEntity.noContent().build()") + w.close("}").blank() + + // M:N traversal scoped to THIS subtype — every relationship it resolves, + // inherited ones (e.g. a base-declared relationship) included. + for (nav in subtypeM2mNavs(st)) { + emitTphSubtypeM2mEndpoint( + w, pkg, table, pkFieldName, plan.discriminatorField, disc, seg, sfx, nav, pkParamType, + m2mHelperNames.getValue(nav), + ) } - appendConstraintHandler() - append("}\n") } + appendConstraintHandler(w) + w.close("}") + val src = w.toString() val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("${shortName}Controller.kt") outFile.parent?.let { Files.createDirectories(it) } @@ -1460,45 +1454,47 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase =\n") - append(" ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any)\n\n") - append(" /**\n") - append(" * A database constraint violation is a CLIENT error, not a 500: the\n") - append(" * identity.reference / identity.secondary that declare these constraints are the\n") - append(" * same metadata this controller already validates against. Anything else is\n") - append(" * rethrown, so the operator keeps the diagnostic and the caller gets none of it.\n") - append(" */\n") + w.line("/** A request body that cannot be read is a client error naming the field, not a 500. */") + w.line("@ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException::class)") + w.line("fun handleUnreadableBody(e: org.springframework.http.converter.HttpMessageNotReadableException): ResponseEntity =") + w.indented { w.line("ResponseEntity.badRequest().body(MetaDecimalWire.unreadableBody(e) as Any)") }.blank() + w.doc( + "A database constraint violation is a CLIENT error, not a 500: the", + "identity.reference / identity.secondary that declare these constraints are the", + "same metadata this controller already validates against. Anything else is", + "rethrown, so the operator keeps the diagnostic and the caller gets none of it.", + ) // java.sql.SQLException TOO, not RuntimeException alone: Exposed raises a violation as // ExposedSQLException, which extends the CHECKED java.sql.SQLException, so a handler for // RuntimeException never matched and Spring answered every conflict with a 500. - append(" @ExceptionHandler(RuntimeException::class, java.sql.SQLException::class)\n") - append(" fun handleConstraintViolation(e: Exception): ResponseEntity {\n") + w.line("@ExceptionHandler(RuntimeException::class, java.sql.SQLException::class)") + w.open("fun handleConstraintViolation(e: Exception): ResponseEntity {") // Depth-bounded and self-reference-guarded: a wrapper whose cause is itself is legal. // SQLState is read via the JDK's own java.sql.SQLException (FQN inline — the #179 guard // forbids surfacing an un-imported type), so no driver is referenced. - append(" val text = generateSequence(e) { if (it.cause === it) null else it.cause }\n") - append(" .take(8)\n") - append(" .flatMap { t -> sequenceOf((t as? java.sql.SQLException)?.sqlState, t.message) }\n") - append(" .filterNotNull()\n") - append(" .joinToString(\" \")\n") - append(" .uppercase()\n") - append(" val kind = when {\n") - append(" \"23503\" in text || \"FOREIGN KEY\" in text || \"SQLITE_CONSTRAINT_FOREIGNKEY\" in text -> \"foreign_key\"\n") - append(" \"23505\" in text || \"UNIQUE CONSTRAINT\" in text || \"SQLITE_CONSTRAINT_UNIQUE\" in text -> \"unique\"\n") - append(" \"23514\" in text || \"CHECK CONSTRAINT\" in text || \"SQLITE_CONSTRAINT_CHECK\" in text -> \"check\"\n") - append(" \"23502\" in text || \"NOT NULL\" in text || \"SQLITE_CONSTRAINT_NOTNULL\" in text -> \"not_null\"\n") - append(" else -> throw e\n") - append(" }\n") - append(" val status = if (kind == \"foreign_key\" || kind == \"unique\") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST\n") - append(" return ResponseEntity.status(status).body(mapOf(\"error\" to \"constraint_violation\", \"constraint\" to kind) as Any)\n") - append(" }\n\n") + w.line("val text = generateSequence(e) { if (it.cause === it) null else it.cause }") + w.indented { + w.line(".take(8)") + w.line(".flatMap { t -> sequenceOf((t as? java.sql.SQLException)?.sqlState, t.message) }") + w.line(".filterNotNull()") + w.line(".joinToString(\" \")") + w.line(".uppercase()") + } + w.open("val kind = when {") + w.line("\"23503\" in text || \"FOREIGN KEY\" in text || \"SQLITE_CONSTRAINT_FOREIGNKEY\" in text -> \"foreign_key\"") + w.line("\"23505\" in text || \"UNIQUE CONSTRAINT\" in text || \"SQLITE_CONSTRAINT_UNIQUE\" in text -> \"unique\"") + w.line("\"23514\" in text || \"CHECK CONSTRAINT\" in text || \"SQLITE_CONSTRAINT_CHECK\" in text -> \"check\"") + w.line("\"23502\" in text || \"NOT NULL\" in text || \"SQLITE_CONSTRAINT_NOTNULL\" in text -> \"not_null\"") + w.line("else -> throw e") + w.close("}") + w.line("val status = if (kind == \"foreign_key\" || kind == \"unique\") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST") + w.line("return ResponseEntity.status(status).body(mapOf(\"error\" to \"constraint_violation\", \"constraint\" to kind) as Any)") + w.close("}").blank() } /** @@ -1518,7 +1514,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase, value: String) { + private fun appendDecimalRangeCheck(w: KotlinWriter, field: MetaField<*>, value: String) { if (field !is DecimalField) return // No @precision: the column is unbounded NUMERIC, so there is no declared range to check // (Java, C#, TypeScript and Python check only a declared precision). @@ -1528,8 +1524,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase>, shortName: String) { - out.append(" val issues = MetaValidationIssues.Collector()\n") - out.append(" if (!body.isObject) return@transaction ResponseEntity.badRequest().body(issues.add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)\n") - out.appendUnknownGuard(shortName) + private fun appendPatchHead(w: KotlinWriter, fields: List>, shortName: String) { + w.line("val issues = MetaValidationIssues.Collector()") + w.line("if (!body.isObject) return@transaction ResponseEntity.badRequest().body(issues.add(\"invalid_type\", emptyList(), \"request body must be a JSON object\").body() as Any)") + appendUnknownGuard(w, shortName) for (field in fields) { if (KotlinGenUtil.isRequiredField(field)) { - out.append(" if (body.has(\"${field.name}\") && body.get(\"${field.name}\").isNull) issues.add(\"invalid_type\", listOf(\"${field.name}\"), \"field '${field.name}' cannot be null\")\n") + w.line("if (body.has(\"${field.name}\") && body.get(\"${field.name}\").isNull) issues.add(\"invalid_type\", listOf(\"${field.name}\"), \"field '${field.name}' cannot be null\")") } } } @@ -1589,14 +1584,14 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase` and `null` are the presence flags the update block reads. */ - private fun appendPatchFieldBinding(out: StringBuilder, field: MetaField<*>, ktType: String, bindExpr: String, validationClass: String) { + private fun appendPatchFieldBinding(w: KotlinWriter, field: MetaField<*>, ktType: String, bindExpr: String, validationClass: String) { val fn = field.name val cap = capitalizeFirst(fn) - out.append(" val has$cap = body.has(\"$fn\")\n") - out.append(" val null$cap = has$cap && body.get(\"$fn\").isNull\n") - out.append(" val v$cap: $ktType? = if (has$cap && !null$cap) issues.bind<$ktType>(\"$fn\") { $bindExpr } else null\n") - out.append(" if (v$cap != null) issues.addAt(validator.validateValue($validationClass, \"$fn\", v$cap), \"$fn\")\n") - out.appendDecimalRangeCheck(" ", field, "v$cap") + w.line("val has$cap = body.has(\"$fn\")") + w.line("val null$cap = has$cap && body.get(\"$fn\").isNull") + w.line("val v$cap: $ktType? = if (has$cap && !null$cap) issues.bind<$ktType>(\"$fn\") { $bindExpr } else null") + w.line("if (v$cap != null) issues.addAt(validator.validateValue($validationClass, \"$fn\", v$cap), \"$fn\")") + appendDecimalRangeCheck(w, field, "v$cap") } /** Capitalize the first char (method-name suffix from a discriminator value). */ @@ -1681,7 +1676,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase */ protected open fun emitFilterPipeline( - out: StringBuilder, + w: KotlinWriter, shortName: String, tableObjectName: String, allowlistName: String, @@ -1692,17 +1687,17 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseFilter // can reference it unqualified. - out.append("/** GENERATED — cross-port cap on `in`-list size (matches TS DEFAULT_MAX_IN_LIST). */\n") - out.append("private const val MAX_IN_LIST = 100\n\n") + w.line("/** GENERATED — cross-port cap on `in`-list size (matches TS DEFAULT_MAX_IN_LIST). */") + w.line("private const val MAX_IN_LIST = 100").blank() - out.append("/** GENERATED — single parsed + validated FR-009 filter predicate. */\n") - out.append("private data class ${shortName}FilterPredicate(val field: String, val op: String, val value: Any?)\n\n") + w.line("/** GENERATED — single parsed + validated FR-009 filter predicate. */") + w.line("private data class ${shortName}FilterPredicate(val field: String, val op: String, val value: Any?)").blank() - out.append("/** GENERATED — parse outcome: predicates, or a cross-port error envelope key + the field it rejected. */\n") + w.line("/** GENERATED — parse outcome: predicates, or a cross-port error envelope key + the field it rejected. */") // `field` is non-null exactly when `error` is — every cross-port filter // envelope names the field it rejected, so the controller can put it // straight into the 400 body. - out.append("private data class ${shortName}FilterResult(val predicates: List<${shortName}FilterPredicate>, val error: String?, val field: String? = null)\n\n") + w.line("private data class ${shortName}FilterResult(val predicates: List<${shortName}FilterPredicate>, val error: String?, val field: String? = null)").blank() // Parser — walks the RAW query string (not Spring's decoded parameter map) and // matches each filter[][]= key against the per-entity FIELDS + @@ -1711,99 +1706,99 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase 0) { out.append(bytes.toString(StandardCharsets.UTF_8)); bytes.reset() }\n") - out.append(" out.append(if (c == '+') ' ' else c)\n") - out.append(" i++\n") - out.append(" }\n") - out.append(" if (bytes.size() > 0) out.append(bytes.toString(StandardCharsets.UTF_8))\n") - out.append(" return out.toString()\n") - out.append("}\n\n") - out.append("private fun Char.isHexDigitAscii(): Boolean = this in '0'..'9' || this in 'a'..'f' || this in 'A'..'F'\n\n") - out.append("/**\n") - out.append(" * GENERATED — parse the bracketed-qs FR-009 filter grammar from the raw query\n") - out.append(" * string. Returns either a list of validated predicates or one of\n") - out.append(" * the cross-port error envelope keys ({@code invalid_filter_field /\n") - out.append(" * invalid_filter_op / invalid_filter_value / filter.in_too_large}) plus the\n") - out.append(" * field each one is about.\n") - out.append(" */\n") - out.append("private fun parse${shortName}Filter(rawQuery: String?): ${shortName}FilterResult {\n") - out.append(" val out = mutableListOf<${shortName}FilterPredicate>()\n") - out.append(" for (pair in rawQuery.orEmpty().split('&')) {\n") - out.append(" if (pair.isEmpty()) continue\n") - out.append(" val eq = pair.indexOf('=')\n") - out.append(" val rawKey = decodeQueryComponent(if (eq < 0) pair else pair.substring(0, eq))\n") - out.append(" val value = decodeQueryComponent(if (eq < 0) \"\" else pair.substring(eq + 1))\n") - out.append(" if (!rawKey.startsWith(\"filter[\")) continue\n") - out.append(" val firstClose = rawKey.indexOf(']', 7)\n") - out.append(" if (firstClose < 0) continue\n") - out.append(" val field = rawKey.substring(7, firstClose)\n") - out.append(" val rest = firstClose + 1\n") - out.append(" val op: String = when {\n") - out.append(" rest >= rawKey.length -> \"eq\"\n") - out.append(" rawKey[rest] == '[' -> {\n") - out.append(" val secondClose = rawKey.indexOf(']', rest + 1)\n") - out.append(" if (secondClose < 0) continue\n") - out.append(" rawKey.substring(rest + 1, secondClose)\n") - out.append(" }\n") - out.append(" else -> continue\n") - out.append(" }\n") - out.append(" if (field !in ${allowlistName}.FIELDS) return ${shortName}FilterResult(emptyList(), \"invalid_filter_field\", field)\n") - out.append(" val ops = ${allowlistName}.OPS_BY_FIELD[field]\n") - out.append(" if (ops == null || op !in ops) return ${shortName}FilterResult(emptyList(), \"invalid_filter_op\", field)\n") - out.append(" val coerced = coerce${shortName}Value(field, op, value)\n") - out.append(" ?: return ${shortName}FilterResult(emptyList(), \"invalid_filter_value\", field)\n") - out.append(" val coercedValue = coerced.value\n") - out.append(" if (op == \"in\" && coercedValue is List<*> && coercedValue.size > MAX_IN_LIST) {\n") - out.append(" return ${shortName}FilterResult(emptyList(), \"filter.in_too_large\", field)\n") - out.append(" }\n") - out.append(" out.add(${shortName}FilterPredicate(field, op, coercedValue))\n") - out.append(" }\n") - out.append(" return ${shortName}FilterResult(out, null)\n") - out.append("}\n\n") + w.doc( + "GENERATED — decode one query component, keeping a malformed escape as written:", + "{@code %XX} is a byte (runs decode as UTF-8), {@code +} is a space, and a {@code %}", + "not followed by two hex digits stays a literal {@code %} — what the TypeScript, C#", + "and Python servers do, where {@code URLDecoder} would throw.", + ) + w.open("private fun decodeQueryComponent(raw: String): String {") + w.line("if ('%' !in raw && '+' !in raw) return raw") + w.line("val out = StringBuilder(raw.length)") + w.line("val bytes = ByteArrayOutputStream()") + w.line("var i = 0") + w.open("while (i < raw.length) {") + w.line("val c = raw[i]") + w.open("if (c == '%' && i + 2 < raw.length && raw[i + 1].isHexDigitAscii() && raw[i + 2].isHexDigitAscii()) {") + w.line("bytes.write(raw.substring(i + 1, i + 3).toInt(16))") + w.line("i += 3") + w.line("continue") + w.close("}") + w.line("if (bytes.size() > 0) { out.append(bytes.toString(StandardCharsets.UTF_8)); bytes.reset() }") + w.line("out.append(if (c == '+') ' ' else c)") + w.line("i++") + w.close("}") + w.line("if (bytes.size() > 0) out.append(bytes.toString(StandardCharsets.UTF_8))") + w.line("return out.toString()") + w.close("}").blank() + w.line("private fun Char.isHexDigitAscii(): Boolean = this in '0'..'9' || this in 'a'..'f' || this in 'A'..'F'").blank() + w.doc( + "GENERATED — parse the bracketed-qs FR-009 filter grammar from the raw query", + "string. Returns either a list of validated predicates or one of", + "the cross-port error envelope keys ({@code invalid_filter_field /", + "invalid_filter_op / invalid_filter_value / filter.in_too_large}) plus the", + "field each one is about.", + ) + w.open("private fun parse${shortName}Filter(rawQuery: String?): ${shortName}FilterResult {") + w.line("val out = mutableListOf<${shortName}FilterPredicate>()") + w.open("for (pair in rawQuery.orEmpty().split('&')) {") + w.line("if (pair.isEmpty()) continue") + w.line("val eq = pair.indexOf('=')") + w.line("val rawKey = decodeQueryComponent(if (eq < 0) pair else pair.substring(0, eq))") + w.line("val value = decodeQueryComponent(if (eq < 0) \"\" else pair.substring(eq + 1))") + w.line("if (!rawKey.startsWith(\"filter[\")) continue") + w.line("val firstClose = rawKey.indexOf(']', 7)") + w.line("if (firstClose < 0) continue") + w.line("val field = rawKey.substring(7, firstClose)") + w.line("val rest = firstClose + 1") + w.open("val op: String = when {") + w.line("rest >= rawKey.length -> \"eq\"") + w.open("rawKey[rest] == '[' -> {") + w.line("val secondClose = rawKey.indexOf(']', rest + 1)") + w.line("if (secondClose < 0) continue") + w.line("rawKey.substring(rest + 1, secondClose)") + w.close("}") + w.line("else -> continue") + w.close("}") + w.line("if (field !in ${allowlistName}.FIELDS) return ${shortName}FilterResult(emptyList(), \"invalid_filter_field\", field)") + w.line("val ops = ${allowlistName}.OPS_BY_FIELD[field]") + w.line("if (ops == null || op !in ops) return ${shortName}FilterResult(emptyList(), \"invalid_filter_op\", field)") + w.line("val coerced = coerce${shortName}Value(field, op, value)") + w.indented { w.line("?: return ${shortName}FilterResult(emptyList(), \"invalid_filter_value\", field)") } + w.line("val coercedValue = coerced.value") + w.open("if (op == \"in\" && coercedValue is List<*> && coercedValue.size > MAX_IN_LIST) {") + w.line("return ${shortName}FilterResult(emptyList(), \"filter.in_too_large\", field)") + w.close("}") + w.line("out.add(${shortName}FilterPredicate(field, op, coercedValue))") + w.close("}") + w.line("return ${shortName}FilterResult(out, null)") + w.close("}").blank() // Boxed result so we can distinguish "coercion failed" (null return) from // "valid null value" (Box(null)). - out.append("/** Box result: null = invalid; Box(value) = coerced. Distinguishes failure from a legitimate null. */\n") - out.append("private data class ${shortName}CoercedValue(val value: Any?)\n\n") + w.line("/** Box result: null = invalid; Box(value) = coerced. Distinguishes failure from a legitimate null. */") + w.line("private data class ${shortName}CoercedValue(val value: Any?)").blank() // Value coercion — split by field then by op. `isNull` is universal (true/false). // `in` returns a List. Scalar ops return the bare Kotlin type for that field. - out.append("private fun coerce${shortName}Value(field: String, op: String, raw: String): ${shortName}CoercedValue? {\n") - out.append(" if (op == \"isNull\") return when (raw) {\n") - out.append(" \"true\" -> ${shortName}CoercedValue(true)\n") - out.append(" \"false\" -> ${shortName}CoercedValue(false)\n") - out.append(" else -> null\n") - out.append(" }\n") - out.append(" return when (field) {\n") + w.open("private fun coerce${shortName}Value(field: String, op: String, raw: String): ${shortName}CoercedValue? {") + w.open("if (op == \"isNull\") return when (raw) {") + w.line("\"true\" -> ${shortName}CoercedValue(true)") + w.line("\"false\" -> ${shortName}CoercedValue(false)") + w.line("else -> null") + w.close("}") + w.open("return when (field) {") for ((fname, subType) in scalarFields) { - out.append(" \"$fname\" -> ") + val arm = "\"$fname\" -> " when (subType) { StringField.SUBTYPE_STRING, EnumField.SUBTYPE_ENUM -> - out.append("if (op == \"in\") ${shortName}CoercedValue(raw.split(\",\").map { it.trim() }) else ${shortName}CoercedValue(raw)\n") + w.line(arm, "if (op == \"in\") ${shortName}CoercedValue(raw.split(\",\").map { it.trim() }) else ${shortName}CoercedValue(raw)") IntegerField.SUBTYPE_INT -> - out.append("coerce${shortName}Int(op, raw)\n") + w.line(arm, "coerce${shortName}Int(op, raw)") LongField.SUBTYPE_LONG, CurrencyField.SUBTYPE_CURRENCY -> - out.append("coerce${shortName}Long(op, raw)\n") + w.line(arm, "coerce${shortName}Long(op, raw)") DoubleField.SUBTYPE_DOUBLE -> - out.append("coerce${shortName}Double(op, raw)\n") + w.line(arm, "coerce${shortName}Double(op, raw)") // The dispatch arm casts the coerced value to the COLUMN's Kotlin type // (`p.value as Float`, `p.value as BigDecimal`), so the coercer must produce // exactly that type. Both used to ride on the Double coercer, and a boxed @@ -1811,63 +1806,63 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase - out.append("coerce${shortName}Float(op, raw)\n") + w.line(arm, "coerce${shortName}Float(op, raw)") DecimalField.SUBTYPE_DECIMAL -> - out.append("coerce${shortName}Decimal(op, raw)\n") + w.line(arm, "coerce${shortName}Decimal(op, raw)") BooleanField.SUBTYPE_BOOLEAN -> - out.append("coerce${shortName}Boolean(op, raw)\n") + w.line(arm, "coerce${shortName}Boolean(op, raw)") DateField.SUBTYPE_DATE -> - out.append("coerce${shortName}Date(op, raw)\n") + w.line(arm, "coerce${shortName}Date(op, raw)") TimestampField.SUBTYPE_TIMESTAMP -> - out.append("coerce${shortName}Timestamp(op, raw)\n") + w.line(arm, "coerce${shortName}Timestamp(op, raw)") TimeField.SUBTYPE_TIME -> - out.append("coerce${shortName}Time(op, raw)\n") + w.line(arm, "coerce${shortName}Time(op, raw)") // uuid columns are Column — the dispatch arm casts `p.value as UUID`, // so the coerced value MUST be a java.util.UUID (allowlist band: // eq/ne/in/isNull). A string passthrough would ClassCastException at runtime. UuidField.SUBTYPE_UUID -> - out.append("coerce${shortName}Uuid(op, raw)\n") + w.line(arm, "coerce${shortName}Uuid(op, raw)") // field.duration columns are Column: the operand is read by the accepted // ISO-8601 rule (MetaDurationWire), a malformed one is `invalid_filter_value`. DurationField.SUBTYPE_DURATION -> - out.append("coerce${shortName}Duration(op, raw)\n") + w.line(arm, "coerce${shortName}Duration(op, raw)") else -> // Unrecognized subtype — fall through to a string pass-through. This branch // is unreachable for fields that are actually @filterable (those subtypes // would have been rejected by the allowlist's op gating already) but covers // the dispatch's `when` exhaustiveness. - out.append("if (op == \"in\") ${shortName}CoercedValue(raw.split(\",\").map { it.trim() }) else ${shortName}CoercedValue(raw)\n") + w.line(arm, "if (op == \"in\") ${shortName}CoercedValue(raw.split(\",\").map { it.trim() }) else ${shortName}CoercedValue(raw)") } } - out.append(" else -> null\n") - out.append(" }\n") - out.append("}\n\n") + w.line("else -> null") + w.close("}") + w.close("}").blank() // Per-type coercion helpers. Each tolerates the `in` operator (returns List) // and the scalar comparison ops (returns the bare type). Parse failure // → null → bubbled up as `invalid_filter_value`. - emitTypedCoercer(out, shortName, "Long", "java.lang.Long.parseLong") - emitTypedCoercer(out, shortName, "Int", "java.lang.Integer.parseInt") - emitTypedCoercer(out, shortName, "Double", "java.lang.Double.parseDouble") + emitTypedCoercer(w, shortName, "Long", "java.lang.Long.parseLong") + emitTypedCoercer(w, shortName, "Int", "java.lang.Integer.parseInt") + emitTypedCoercer(w, shortName, "Double", "java.lang.Double.parseDouble") // Emitted only when such a column exists, so a model without one keeps its bytes. if (scalarFields.any { it.subType == FloatField.SUBTYPE_FLOAT }) { - emitTypedCoercer(out, shortName, "Float", "java.lang.Float.parseFloat") + emitTypedCoercer(w, shortName, "Float", "java.lang.Float.parseFloat") } if (scalarFields.any { it.subType == DecimalField.SUBTYPE_DECIMAL }) { // W2: the operand is parsed by the shared canonical grammar and compared exactly (never // through a double); a malformed or out-of-range one is null, so `invalid_filter_value`. - emitTypedCoercer(out, shortName, "Decimal", "MetaDecimalWire.parseFilterOperand") + emitTypedCoercer(w, shortName, "Decimal", "MetaDecimalWire.parseFilterOperand") } - emitTypedCoercer(out, shortName, "Date", "LocalDate.parse") - emitTypedCoercer(out, shortName, "Time", "LocalTime.parse") + emitTypedCoercer(w, shortName, "Date", "LocalDate.parse") + emitTypedCoercer(w, shortName, "Time", "LocalTime.parse") // uuid coercer — emitted only when a uuid column exists (its `UUID.fromString` // needs the conditional java.util.UUID import) so uuid-free entities stay // byte-identical to pre-uuid output. if (scalarFields.any { it.subType == UuidField.SUBTYPE_UUID }) { - emitTypedCoercer(out, shortName, "Uuid", "UUID.fromString") + emitTypedCoercer(w, shortName, "Uuid", "UUID.fromString") } if (scalarFields.any { it.subType == DurationField.SUBTYPE_DURATION }) { - emitTypedCoercer(out, shortName, "Duration", "MetaDurationWire.parse") + emitTypedCoercer(w, shortName, "Duration", "MetaDurationWire.parse") } // Timestamp coercer. ADR-0036 Wave 2: a default `field.timestamp` column is an // absolute `java.time.Instant` (its WHERE-arm casts `p.value as Instant`), so the @@ -1883,35 +1878,35 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase Instant? = { s ->\n") - out.append(" val withZone = if (s.endsWith(\"Z\") || s.contains(\"+\")) s else s + \"Z\"\n") - out.append(" runCatching { Instant.parse(withZone) }.getOrNull()\n") - out.append(" }\n") + w.open("val parse: (String) -> Instant? = { s ->") + w.line("val withZone = if (s.endsWith(\"Z\") || s.contains(\"+\")) s else s + \"Z\"") + w.line("runCatching { Instant.parse(withZone) }.getOrNull()") + w.close("}") } else { - out.append(" val parse: (String) -> LocalDateTime? = { s -> runCatching { LocalDateTime.parse(s, ${shortName}TimestampFmt) }.getOrNull() }\n") - } - out.append(" if (op == \"in\") {\n") - out.append(" val parts = raw.split(\",\").map { it.trim() }\n") - out.append(" val list = parts.map { parse(it) ?: return null }\n") - out.append(" return ${shortName}CoercedValue(list)\n") - out.append(" }\n") - out.append(" return ${shortName}CoercedValue(parse(raw) ?: return null)\n") - out.append("}\n\n") + w.line("val parse: (String) -> LocalDateTime? = { s -> runCatching { LocalDateTime.parse(s, ${shortName}TimestampFmt) }.getOrNull() }") + } + w.open("if (op == \"in\") {") + w.line("val parts = raw.split(\",\").map { it.trim() }") + w.line("val list = parts.map { parse(it) ?: return null }") + w.line("return ${shortName}CoercedValue(list)") + w.close("}") + w.line("return ${shortName}CoercedValue(parse(raw) ?: return null)") + w.close("}").blank() // Boolean has its own non-throwing parse (when/else) — can't ride on // runCatching, which would convert a malformed input to a thrown // IllegalArgumentException then swallow it. - out.append("private fun coerce${shortName}Boolean(op: String, raw: String): ${shortName}CoercedValue? {\n") - out.append(" val parse: (String) -> Boolean? = { s -> when (s) { \"true\" -> true; \"false\" -> false; else -> null } }\n") - out.append(" if (op == \"in\") {\n") - out.append(" val parts = raw.split(\",\").map { it.trim() }\n") - out.append(" val list = parts.map { parse(it) ?: return null }\n") - out.append(" return ${shortName}CoercedValue(list)\n") - out.append(" }\n") - out.append(" return ${shortName}CoercedValue(parse(raw) ?: return null)\n") - out.append("}\n\n") + w.open("private fun coerce${shortName}Boolean(op: String, raw: String): ${shortName}CoercedValue? {") + w.line("val parse: (String) -> Boolean? = { s -> when (s) { \"true\" -> true; \"false\" -> false; else -> null } }") + w.open("if (op == \"in\") {") + w.line("val parts = raw.split(\",\").map { it.trim() }") + w.line("val list = parts.map { parse(it) ?: return null }") + w.line("return ${shortName}CoercedValue(list)") + w.close("}") + w.line("return ${shortName}CoercedValue(parse(raw) ?: return null)") + w.close("}").blank() // Exposed `Op` dispatch. Per-field arm is inlined directly in // WhereOp under a single `with(SqlExpressionBuilder)` block. This @@ -1919,31 +1914,31 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase}, AND-combining each predicate's column-op-value triple\n") - out.append(" * against ${tableObjectName}. Returns null when [predicates] is empty so the\n") - out.append(" * caller can elide the WHERE clause entirely.\n") - out.append(" */\n") - out.append("@Suppress(\"UNCHECKED_CAST\")\n") - out.append("private fun ${shortName}WhereOp(predicates: List<${shortName}FilterPredicate>): Op? {\n") - out.append(" if (predicates.isEmpty()) return null\n") + w.doc( + "GENERATED — fold a list of validated predicates into an Exposed", + "{@code Op}, AND-combining each predicate's column-op-value triple", + "against ${tableObjectName}. Returns null when [predicates] is empty so the", + "caller can elide the WHERE clause entirely.", + ) + w.line("@Suppress(\"UNCHECKED_CAST\")") + w.open("private fun ${shortName}WhereOp(predicates: List<${shortName}FilterPredicate>): Op? {") + w.line("if (predicates.isEmpty()) return null") // issue #390: under 1.x the column operators emitPerFieldDispatchArm emits below // (eq/less/greater/inList/like/castTo) are plain top-level imports, not // SqlExpressionBuilder-scoped members — this function needs no `with(...)` receiver // at all. The per-field loop body is IDENTICAL text either way (indentation is // cosmetic in Kotlin); only the opening/closing frame differs. if (api == ExposedApi.V1) { - out.append(" var combined: Op? = null\n") + w.line("var combined: Op? = null") } else { - out.append(" return with(SqlExpressionBuilder) {\n") - out.append(" var combined: Op? = null\n") + w.open("return with(SqlExpressionBuilder) {") + w.line("var combined: Op? = null") } - out.append(" for (p in predicates) {\n") - out.append(" val op: Op = when (p.field) {\n") + w.open("for (p in predicates) {") + w.open("val op: Op = when (p.field) {") for ((fname, subType, elementType, intBackedEnumType) in scalarFields) { emitPerFieldDispatchArm( - out, + w, tableObjectName = tableObjectName, fieldName = fname, elementType = elementType, @@ -1952,17 +1947,17 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase continue\n") - out.append(" }\n") - out.append(" combined = combined?.and(op) ?: op\n") - out.append(" }\n") + w.line("else -> continue") + w.close("}") + w.line("combined = combined?.and(op) ?: op") + w.close("}") if (api == ExposedApi.V1) { - out.append(" return combined\n") + w.line("return combined") } else { - out.append(" combined\n") - out.append(" }\n") + w.line("combined") + w.close("}") } - out.append("}\n\n") + w.close("}").blank() } /** @@ -1974,7 +1969,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase when (p.op) {\n") - out.append(" \"eq\" -> $member?.let { $col eq it } ?: Op.FALSE\n") - out.append(" \"ne\" -> $member?.let { $col neq it } ?: $col.isNotNull()\n") - out.append(" \"in\" -> $col inList (p.value as List).mapNotNull { s -> $intBackedEnumType.entries.firstOrNull { it.name == s } }\n") - out.append(" \"isNull\" -> if (p.value as Boolean) $col.isNull() else $col.isNotNull()\n") - out.append(" else -> throw IllegalStateException(\"unsupported op for $fieldName: \" + p.op)\n") - out.append(" }\n") + w.open("\"$fieldName\" -> when (p.op) {") + w.line("\"eq\" -> $member?.let { $col eq it } ?: Op.FALSE") + w.line("\"ne\" -> $member?.let { $col neq it } ?: $col.isNotNull()") + w.line("\"in\" -> $col inList (p.value as List).mapNotNull { s -> $intBackedEnumType.entries.firstOrNull { it.name == s } }") + w.line("\"isNull\" -> if (p.value as Boolean) $col.isNull() else $col.isNotNull()") + w.line("else -> throw IllegalStateException(\"unsupported op for $fieldName: \" + p.op)") + w.close("}") return } // Exposed's typed `Column.eq(t: T)` / `.neq` / `.inList(Iterable)` reject a @@ -2019,19 +2014,19 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase(TextColumnType())" else column - out.append(" \"$fieldName\" -> when (p.op) {\n") - out.append(" \"eq\" -> $col eq (p.value as $elementType)\n") + w.open("\"$fieldName\" -> when (p.op) {") + w.line("\"eq\" -> $col eq (p.value as $elementType)") if (FilterOps.FILTER_OP_NE in band) { - out.append(" \"ne\" -> $col neq (p.value as $elementType)\n") + w.line("\"ne\" -> $col neq (p.value as $elementType)") } if (FilterOps.FILTER_OP_GT in band) { - out.append(" \"gt\" -> $col greater (p.value as $elementType)\n") - out.append(" \"gte\" -> $col greaterEq (p.value as $elementType)\n") - out.append(" \"lt\" -> $col less (p.value as $elementType)\n") - out.append(" \"lte\" -> $col lessEq (p.value as $elementType)\n") + w.line("\"gt\" -> $col greater (p.value as $elementType)") + w.line("\"gte\" -> $col greaterEq (p.value as $elementType)") + w.line("\"lt\" -> $col less (p.value as $elementType)") + w.line("\"lte\" -> $col lessEq (p.value as $elementType)") } if (FilterOps.FILTER_OP_IN in band) { - out.append(" \"in\" -> $col inList (p.value as List<$elementType>)\n") + w.line("\"in\" -> $col inList (p.value as List<$elementType>)") } if (FilterOps.FILTER_OP_LIKE in band) { // Exposed's `like` extension requires a String-typed expression. An isEnum field's @@ -2044,11 +2039,11 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase(TextColumnType())" - out.append(" \"like\" -> $likeCol like (p.value as String)\n") + w.line("\"like\" -> $likeCol like (p.value as String)") } - out.append(" \"isNull\" -> if (p.value as Boolean) $column.isNull() else $column.isNotNull()\n") - out.append(" else -> throw IllegalStateException(\"unsupported op for $fieldName: \" + p.op)\n") - out.append(" }\n") + w.line("\"isNull\" -> if (p.value as Boolean) $column.isNull() else $column.isNotNull()") + w.line("else -> throw IllegalStateException(\"unsupported op for $fieldName: \" + p.op)") + w.close("}") } /** @@ -2058,20 +2053,20 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase Any? = { s -> runCatching { $parseFn(s) }.getOrNull() }\n") - out.append(" if (op == \"in\") {\n") - out.append(" val parts = raw.split(\",\").map { it.trim() }\n") - out.append(" val list = parts.map { parse(it) ?: return null }\n") - out.append(" return ${shortName}CoercedValue(list)\n") - out.append(" }\n") - out.append(" return ${shortName}CoercedValue(parse(raw) ?: return null)\n") - out.append("}\n\n") + w.open("private fun coerce${shortName}${typeSuffix}(op: String, raw: String): ${shortName}CoercedValue? {") + w.line("val parse: (String) -> Any? = { s -> runCatching { $parseFn(s) }.getOrNull() }") + w.open("if (op == \"in\") {") + w.line("val parts = raw.split(\",\").map { it.trim() }") + w.line("val list = parts.map { parse(it) ?: return null }") + w.line("return ${shortName}CoercedValue(list)") + w.close("}") + w.line("return ${shortName}CoercedValue(parse(raw) ?: return null)") + w.close("}").blank() } /** @@ -2089,7 +2084,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase> = transaction {\n") - appendM2mRows(out, nav, targetType, "$sourceTable.$queryFnName(id)") - out.append(" }\n") + w.blank() + w.line("/** M:N traversal: the ${nav.targetShortName} rows related to this $sourceShort through ${nav.junctionShortName}$symMarker. */") + w.line("@GetMapping(\"/{id}/${nav.relationName}\")") + w.open("fun ${nav.relationName}(@PathVariable id: $pkParamType): ResponseEntity> = transaction {") + appendM2mRows(w, nav, targetType, "$sourceTable.$queryFnName(id)") + w.close("}") } /** #484: the element type an M:N traversal answers — `Any` (a redacted tree) when the target has a credential. */ @@ -2124,20 +2119,20 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase" else ""} = $query.map { row ->\n") - if (creds.isNotEmpty()) out.append(" stripCredentials(\n objectMapper,\n") - out.append(" $targetType(\n") + w.open("val rows${if (creds.isNotEmpty()) ": List" else ""} = $query.map { row ->") + if (creds.isNotEmpty()) w.open("stripCredentials(").line("objectMapper,") + w.open("$targetType(") for (fname in nav.targetScalarFields) { - out.append(" $fname = row[${nav.targetTableObj}.$fname],\n") + w.line("$fname = row[${nav.targetTableObj}.$fname],") } - out.append(" )${if (creds.isNotEmpty()) "," else ""}\n") + w.close(")${if (creds.isNotEmpty()) "," else ""}") if (creds.isNotEmpty()) { - out.append(" ${creds.joinToString(", ") { "\"$it\"" }},\n )\n") + w.line("${creds.joinToString(", ") { "\"$it\"" }},").close(")") } - out.append(" }\n") - out.append(" ResponseEntity.ok(rows)\n") + w.close("}") + w.line("ResponseEntity.ok(rows)") } /** @@ -2155,7 +2150,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase` segment would be decorative. */ protected open fun emitTphSubtypeM2mEndpoint( - out: StringBuilder, + w: KotlinWriter, sourcePkg: String, table: String, pkFieldName: String, @@ -2173,16 +2168,16 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase> = transaction {\n") - out.append(" if ($table.selectAll().where { ($table.$pkFieldName eq id) and ($table.$discField eq $discExpr) }.singleOrNull() == null) {\n") - out.append(" return@transaction ResponseEntity.ok(emptyList<$elem>())\n") - out.append(" }\n") - appendM2mRows(out, nav, targetType, "$table.$queryFnName(id)") - out.append(" }\n") + w.open("fun ${nav.relationName}$sfx(@PathVariable id: $pkParamType): ResponseEntity> = transaction {") + w.open("if ($table.selectAll().where { ($table.$pkFieldName eq id) and ($table.$discField eq $discExpr) }.singleOrNull() == null) {") + w.line("return@transaction ResponseEntity.ok(emptyList<$elem>())") + w.close("}") + appendM2mRows(w, nav, targetType, "$table.$queryFnName(id)") + w.close("}") } /** @@ -2345,125 +2340,124 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase = methodNotAllowed()\n\n") - if (hasItem) { - // One mapping for all three item verbs: the bodies are identical. Stacking - // @PatchMapping + @PutMapping on one method does NOT register both in Spring - // MVC (see emit()), so the method= list is the form that works. The path - // variable is deliberately unbound — the row is never read. - append(" @RequestMapping(value = [\"/{id}\"], method = [RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.DELETE])\n") - append(" fun rejectItemWrite(): ResponseEntity = methodNotAllowed()\n\n") - } - // `message` is free prose and deliberately outside the asserted contract, so this - // port spells it once rather than threading the verb through every handler. - append(" private fun methodNotAllowed(): ResponseEntity =\n") - append(" ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(\n") - append(" mapOf(\n") - append(" \"error\" to \"method_not_allowed\",\n") - append(" \"message\" to \"writes are not supported on a $noun (read-only).\",\n") - append(" ) as Any\n") - append(" )\n") - append("}\n") + w.line("@PostMapping") + w.line("fun create(): ResponseEntity = methodNotAllowed()").blank() + if (hasItem) { + // One mapping for all three item verbs: the bodies are identical. Stacking + // @PatchMapping + @PutMapping on one method does NOT register both in Spring + // MVC (see emit()), so the method= list is the form that works. The path + // variable is deliberately unbound — the row is never read. + w.line("@RequestMapping(value = [\"/{id}\"], method = [RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.DELETE])") + w.line("fun rejectItemWrite(): ResponseEntity = methodNotAllowed()").blank() } + // `message` is free prose and deliberately outside the asserted contract, so this + // port spells it once rather than threading the verb through every handler. + w.line("private fun methodNotAllowed(): ResponseEntity =") + w.indented { + w.open("ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(") + w.open("mapOf(") + w.line("\"error\" to \"method_not_allowed\",") + w.line("\"message\" to \"writes are not supported on a $noun (read-only).\",") + w.close(") as Any") + w.close(")") + } + w.close("}") + val source = w.toString() val outFile = outRoot.resolve(pkg.replace('.', '/')) .resolve(KotlinNaming.controllerName(shortName) + ".kt") @@ -2484,44 +2478,44 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseSort` helper. */ private fun appendSortSurface( - sb: StringBuilder, shortName: String, entity: MetaObject, sortFields: List - ) = with(sb) { + w: KotlinWriter, shortName: String, entity: MetaObject, sortFields: List + ) { // Sort allowlist — static set; unknown fields → 400. Emitted at file level so it // remains accessible to the handler functions without polluting the controller's // surface. - append("/** GENERATED — sort allowlist for ${shortName} (cross-port API contract). */\n") - append("private val ${shortName}SortAllowlist = setOf(\n") + w.line("/** GENERATED — sort allowlist for ${shortName} (cross-port API contract). */") + w.open("private val ${shortName}SortAllowlist = setOf(") for (field in sortFields) { - append(" \"$field\",\n") + w.line("\"$field\",") } - append(")\n\n") - appendSortDefaultOrders(this, shortName, entity, sortFields) + w.close(")").blank() + appendSortDefaultOrders(w, shortName, entity, sortFields) // parseSort: returns (field, asc|desc) or null for malformed/disallowed input. // Returning null lets the handler emit the 400 envelope itself rather than // throwing — cleaner separation. Inlined per-entity so the allowlist closes // over the right set without a runtime parameter. - append("private fun parse${shortName}Sort(raw: String): Pair? {\n") - append(" val parts = raw.split(\":\", limit = 2)\n") - append(" val field = parts.getOrNull(0) ?: return null\n") - append(" if (field !in ${shortName}SortAllowlist) return null\n") + w.open("private fun parse${shortName}Sort(raw: String): Pair? {") + w.line("val parts = raw.split(\":\", limit = 2)") + w.line("val field = parts.getOrNull(0) ?: return null") + w.line("if (field !in ${shortName}SortAllowlist) return null") // `?sort=field` with no `:order` takes the field's DECLARED @sortableDefaultOrder. // The "asc" fallback stays at the READ, one place per port. - append(" val dirRaw = parts.getOrNull(1)?.lowercase()\n") - append(" ?: ${shortName}SortDefaultOrder[field] ?: \"asc\"\n") - append(" val dir = when (dirRaw) {\n") - append(" \"asc\" -> SortOrder.ASC_NULLS_LAST\n") - append(" \"desc\" -> SortOrder.DESC_NULLS_FIRST\n") - append(" else -> return null\n") - append(" }\n") - append(" return field to dir\n") - append("}\n\n") + w.line("val dirRaw = parts.getOrNull(1)?.lowercase()") + w.indented { w.line("?: ${shortName}SortDefaultOrder[field] ?: \"asc\"") } + w.open("val dir = when (dirRaw) {") + w.line("\"asc\" -> SortOrder.ASC_NULLS_LAST") + w.line("\"desc\" -> SortOrder.DESC_NULLS_FIRST") + w.line("else -> return null") + w.close("}") + w.line("return field to dir") + w.close("}").blank() } /** `rowTo` — an Exposed ResultRow mapped to the generated data class. */ private fun appendRowToMapper( - sb: StringBuilder, shortName: String, entity: MetaObject, readObj: String - ) = with(sb) { + w: KotlinWriter, shortName: String, entity: MetaObject, readObj: String + ) { // rowTo: ResultRow → data class. Program D: a field.object value-object jsonb // column IS read here — the Exposed Column codec (the shared Jackson metaJsonbMapper) // already decodes the jsonb text to the VO record / List, so `row[Table.col]` yields @@ -2530,64 +2524,64 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase`) are skipped — the data class defaults them. if ((field is MapField && !isVoMapColumn(field)) || (field is ObjectField && !isJsonbObjectColumn(field))) continue // The column PROPERTY, which the table generator renames when the field name is a // member of Exposed's Table (`source` is declared `sourceColumn`). Identity otherwise. - append(" ${field.name} = row[${readObj}.${KotlinNaming.safeColumnProperty(field.name, exposedApi())}],\n") + w.line("${field.name} = row[${readObj}.${KotlinNaming.safeColumnProperty(field.name, exposedApi())}],") } - append(")\n\n") + w.close(")").blank() } /** GET (list) — pagination + sort + withCount + the FR-009 filter operators. */ private fun appendListHandler( - sb: StringBuilder, shortName: String, readObj: String, sortFields: List, + w: KotlinWriter, shortName: String, readObj: String, sortFields: List, creds: Collection = emptyList(), - ) = with(sb) { + ) { val api = exposedApi() // List handler — pagination + sort + withCount + FR-009 filter operators. // // The filter reads `request.queryString` raw rather than Spring's parameter map: // Tomcat drops a parameter holding a malformed escape, which silently unfiltered // the list (see parseFilter). - append(" @GetMapping\n") - append(" fun list(\n") - append(" @RequestParam(required = false) limit: Int?,\n") - append(" @RequestParam(required = false) offset: Int?,\n") - append(" @RequestParam(required = false) sort: String?,\n") - append(" @RequestParam(required = false, name = \"withCount\") withCount: Int?,\n") - append(" request: HttpServletRequest,\n") - append(" ): ResponseEntity = transaction {\n") - appendLimitGuard() - append(" // FR-009 filter operators — short-circuit 400 on invalid field/op/value.\n") - append(" val filterResult = parse${shortName}Filter(request.queryString)\n") - append(" if (filterResult.error != null) {\n") - append(" return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)\n") - append(" }\n") - append(" val whereOp = ${shortName}WhereOp(filterResult.predicates)\n") - append(" var q = if (whereOp != null) ${readObj}.selectAll().where { whereOp } else ${readObj}.selectAll()\n") - append(" if (sort != null) {\n") - append(" val parsed = parse${shortName}Sort(sort)\n") - append(" ?: return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)\n") - append(" val (field, dir) = parsed\n") - append(" q = q.orderBy(${sortColumnExpr(readObj, shortName, sortFields, exposedApi())} to dir)\n") - append(" }\n") - append(" val total: Long = if (withCount == 1) q.count() else -1L\n") - append(" val effectiveLimit = limit ?: ${defaultLimit()}\n") - append(" val effectiveOffset = (offset ?: 0).toLong()\n") + w.line("@GetMapping") + w.open("fun list(") + w.line("@RequestParam(required = false) limit: Int?,") + w.line("@RequestParam(required = false) offset: Int?,") + w.line("@RequestParam(required = false) sort: String?,") + w.line("@RequestParam(required = false, name = \"withCount\") withCount: Int?,") + w.line("request: HttpServletRequest,") + w.reopen("): ResponseEntity = transaction {") + appendLimitGuard(w) + w.line("// FR-009 filter operators — short-circuit 400 on invalid field/op/value.") + w.line("val filterResult = parse${shortName}Filter(request.queryString)") + w.open("if (filterResult.error != null) {") + w.line("return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)") + w.close("}") + w.line("val whereOp = ${shortName}WhereOp(filterResult.predicates)") + w.line("var q = if (whereOp != null) ${readObj}.selectAll().where { whereOp } else ${readObj}.selectAll()") + w.open("if (sort != null) {") + w.line("val parsed = parse${shortName}Sort(sort)") + w.indented { w.line("?: return@transaction ResponseEntity.badRequest().body(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)") } + w.line("val (field, dir) = parsed") + writeOrderBy(w, readObj, shortName, sortFields, exposedApi()) + w.close("}") + w.line("val total: Long = if (withCount == 1) q.count() else -1L") + w.line("val effectiveLimit = limit ?: ${defaultLimit()}") + w.line("val effectiveOffset = (offset ?: 0).toLong()") // issue #390: see the vanilla/TPH controllers' identical comment above. if (api == ExposedApi.V1) { - append(" val rows = q.limit(effectiveLimit).offset(effectiveOffset).map { ${wireRow(shortName, creds, "it")} }\n") + w.line("val rows = q.limit(effectiveLimit).offset(effectiveOffset).map { ${wireRow(shortName, creds, "it")} }") } else { - append(" val rows = q.limit(effectiveLimit, effectiveOffset).map { ${wireRow(shortName, creds, "it")} }\n") + w.line("val rows = q.limit(effectiveLimit, effectiveOffset).map { ${wireRow(shortName, creds, "it")} }") } - append(" if (withCount == 1) ResponseEntity.ok(mapOf(\"rows\" to rows, \"total\" to total) as Any)\n") - append(" else ResponseEntity.ok(rows as Any)\n") - append(" }\n\n") + w.line("if (withCount == 1) ResponseEntity.ok(mapOf(\"rows\" to rows, \"total\" to total) as Any)") + w.line("else ResponseEntity.ok(rows as Any)") + w.close("}").blank() } /** @@ -2599,9 +2593,9 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase, maxRows: Int, + w: KotlinWriter, shortName: String, readObj: String, sortFields: List, maxRows: Int, export: Boolean, creds: Collection = emptyList(), - ) = with(sb) { + ) { val api = exposedApi() // With the export branch wired, no answer of the list route consults Accept (the selector // is ?format): every body carries an explicit application/json, which Spring honours @@ -2609,66 +2603,66 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase =\n") - append(" if (format != null) export(format, limit, offset, sort, withCount, request)\n") - append(" else listRows(limit, offset, sort, withCount, request)\n\n") - append(" private fun listRows(\n") - append(" limit: String?, offset: String?, sort: String?, withCount: String?, request: HttpServletRequest,\n") - append(" ): ResponseEntity = transaction {\n") + w.close("): ResponseEntity =") + w.indented { w.line("if (format != null) export(format, limit, offset, sort, withCount, request)") } + w.indented { w.line("else listRows(limit, offset, sort, withCount, request)") }.blank() + w.open("private fun listRows(") + w.line("limit: String?, offset: String?, sort: String?, withCount: String?, request: HttpServletRequest,") + w.reopen("): ResponseEntity = transaction {") } else { - append(" ): ResponseEntity = transaction {\n") + w.reopen("): ResponseEntity = transaction {") } val withCountOne = if (export) "withCount == \"1\"" else "withCount == 1" - append(" val maxRows = $maxRows\n") - append(" val tooLarge = ${bad}mapOf(\"error\" to \"report_too_large\", \"maxRows\" to maxRows) as Any)\n") - append(" var requestedLimit: Int? = null\n") - append(" if (limit != null) {\n") - append(" val n = limit.toLongOrNull()?.takeIf { it >= 1 }\n") - append(" ?: return@transaction ${bad}mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"limit\", \"value\" to limit, \"expected\" to \"an integer from 1 to \$maxRows\") as Any)\n") - append(" if (n > maxRows) return@transaction tooLarge\n") - append(" requestedLimit = n.toInt()\n") - append(" }\n") - append(" val effectiveOffset: Long = if (offset == null) 0L else offset.toLongOrNull()?.takeIf { it >= 0 }\n") - append(" ?: return@transaction ${bad}mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"offset\", \"value\" to offset, \"expected\" to \"a non-negative integer (0 or more)\") as Any)\n") - append(" val filterResult = parse${shortName}Filter(request.queryString)\n") - append(" if (filterResult.error != null) {\n") - append(" return@transaction ${bad}mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)\n") - append(" }\n") - append(" val whereOp = ${shortName}WhereOp(filterResult.predicates)\n") - append(" var q = if (whereOp != null) ${readObj}.selectAll().where { whereOp } else ${readObj}.selectAll()\n") - append(" if (sort != null) {\n") - append(" val parsed = parse${shortName}Sort(sort)\n") - append(" ?: return@transaction ${bad}mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)\n") - append(" val (field, dir) = parsed\n") - append(" q = q.orderBy(${sortColumnExpr(readObj, shortName, sortFields, api)} to dir)\n") - append(" }\n") - append(" val total: Long = if ($withCountOne) q.count() else -1L\n") - append(" val effectiveLimit = requestedLimit ?: (maxRows + 1)\n") + w.line("val maxRows = $maxRows") + w.line("val tooLarge = ${bad}mapOf(\"error\" to \"report_too_large\", \"maxRows\" to maxRows) as Any)") + w.line("var requestedLimit: Int? = null") + w.open("if (limit != null) {") + w.line("val n = limit.toLongOrNull()?.takeIf { it >= 1 }") + w.indented { w.line("?: return@transaction ${bad}mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"limit\", \"value\" to limit, \"expected\" to \"an integer from 1 to \$maxRows\") as Any)") } + w.line("if (n > maxRows) return@transaction tooLarge") + w.line("requestedLimit = n.toInt()") + w.close("}") + w.line("val effectiveOffset: Long = if (offset == null) 0L else offset.toLongOrNull()?.takeIf { it >= 0 }") + w.indented { w.line("?: return@transaction ${bad}mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"offset\", \"value\" to offset, \"expected\" to \"a non-negative integer (0 or more)\") as Any)") } + w.line("val filterResult = parse${shortName}Filter(request.queryString)") + w.open("if (filterResult.error != null) {") + w.line("return@transaction ${bad}mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field) as Any)") + w.close("}") + w.line("val whereOp = ${shortName}WhereOp(filterResult.predicates)") + w.line("var q = if (whereOp != null) ${readObj}.selectAll().where { whereOp } else ${readObj}.selectAll()") + w.open("if (sort != null) {") + w.line("val parsed = parse${shortName}Sort(sort)") + w.indented { w.line("?: return@transaction ${bad}mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')) as Any)") } + w.line("val (field, dir) = parsed") + writeOrderBy(w, readObj, shortName, sortFields, api) + w.close("}") + w.line("val total: Long = if ($withCountOne) q.count() else -1L") + w.line("val effectiveLimit = requestedLimit ?: (maxRows + 1)") if (api == ExposedApi.V1) { - append(" val rows = q.limit(effectiveLimit).offset(effectiveOffset).map { ${wireRow(shortName, creds, "it")} }\n") + w.line("val rows = q.limit(effectiveLimit).offset(effectiveOffset).map { ${wireRow(shortName, creds, "it")} }") } else { - append(" val rows = q.limit(effectiveLimit, effectiveOffset).map { ${wireRow(shortName, creds, "it")} }\n") + w.line("val rows = q.limit(effectiveLimit, effectiveOffset).map { ${wireRow(shortName, creds, "it")} }") } - append(" if (requestedLimit == null && rows.size > maxRows) return@transaction tooLarge\n") - append(" if ($withCountOne) ${okBody}mapOf(\"rows\" to rows, \"total\" to total) as Any)\n") - append(" else ${okBody}rows as Any)\n") - append(" }\n\n") - if (export) appendReportExportHandler(this, shortName, readObj, sortFields, creds) + w.line("if (requestedLimit == null && rows.size > maxRows) return@transaction tooLarge") + w.line("if ($withCountOne) ${okBody}mapOf(\"rows\" to rows, \"total\" to total) as Any)") + w.line("else ${okBody}rows as Any)") + w.close("}").blank() + if (export) appendReportExportHandler(w, shortName, readObj, sortFields, creds) } /** @@ -2682,75 +2676,77 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase, + w: KotlinWriter, shortName: String, readObj: String, sortFields: List, creds: Collection = emptyList(), - ) = with(sb) { + ) { val api = exposedApi() val x = "${shortName}Export" - append(" private fun export(\n") - append(" format: String, limit: String?, offset: String?, sort: String?, withCount: String?, request: HttpServletRequest,\n") - append(" ): ResponseEntity = transaction {\n") - append(" val maxRows = $x.MAX_ROWS\n") - append(" if (!$x.isFormat(format)) return@transaction jsonBadRequest($x.invalidFormat())\n") - append(" if (format != \"json\" && $x.isTruthy(withCount)) return@transaction jsonBadRequest($x.withCountRefused())\n") - append(" var requestedLimit: Int? = null\n") - append(" if (limit != null) {\n") - append(" val n = limit.toLongOrNull()?.takeIf { it >= 1 }\n") - append(" ?: return@transaction jsonBadRequest(mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"limit\", \"value\" to limit, \"expected\" to \"an integer from 1 to \$maxRows\"))\n") - append(" if (n > maxRows) return@transaction jsonBadRequest($x.tooLarge())\n") - append(" requestedLimit = n.toInt()\n") - append(" }\n") - append(" val effectiveOffset: Long = if (offset == null) 0L else offset.toLongOrNull()?.takeIf { it >= 0 }\n") - append(" ?: return@transaction jsonBadRequest(mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"offset\", \"value\" to offset, \"expected\" to \"a non-negative integer (0 or more)\"))\n") - append(" val filterResult = parse${shortName}Filter(request.queryString)\n") - append(" if (filterResult.error != null) {\n") - append(" return@transaction jsonBadRequest(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field))\n") - append(" }\n") - append(" val whereOp = ${shortName}WhereOp(filterResult.predicates)\n") - append(" var q = if (whereOp != null) ${readObj}.selectAll().where { whereOp } else ${readObj}.selectAll()\n") - append(" if (sort != null) {\n") - append(" val parsed = parse${shortName}Sort(sort)\n") - append(" ?: return@transaction jsonBadRequest(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')))\n") - append(" val (field, dir) = parsed\n") - append(" q = q.orderBy(${sortColumnExpr(readObj, shortName, sortFields, api)} to dir)\n") - append(" }\n") - append(" val total: Long = if (withCount == \"1\") q.count() else -1L\n") - append(" val effectiveLimit = requestedLimit ?: (maxRows + 1)\n") + w.open("private fun export(") + w.line("format: String, limit: String?, offset: String?, sort: String?, withCount: String?, request: HttpServletRequest,") + w.reopen("): ResponseEntity = transaction {") + w.line("val maxRows = $x.MAX_ROWS") + w.line("if (!$x.isFormat(format)) return@transaction jsonBadRequest($x.invalidFormat())") + w.line("if (format != \"json\" && $x.isTruthy(withCount)) return@transaction jsonBadRequest($x.withCountRefused())") + w.line("var requestedLimit: Int? = null") + w.open("if (limit != null) {") + w.line("val n = limit.toLongOrNull()?.takeIf { it >= 1 }") + w.indented { w.line("?: return@transaction jsonBadRequest(mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"limit\", \"value\" to limit, \"expected\" to \"an integer from 1 to \$maxRows\"))") } + w.line("if (n > maxRows) return@transaction jsonBadRequest($x.tooLarge())") + w.line("requestedLimit = n.toInt()") + w.close("}") + w.line("val effectiveOffset: Long = if (offset == null) 0L else offset.toLongOrNull()?.takeIf { it >= 0 }") + w.indented { w.line("?: return@transaction jsonBadRequest(mapOf(\"error\" to \"pagination.invalid_value\", \"param\" to \"offset\", \"value\" to offset, \"expected\" to \"a non-negative integer (0 or more)\"))") } + w.line("val filterResult = parse${shortName}Filter(request.queryString)") + w.open("if (filterResult.error != null) {") + w.line("return@transaction jsonBadRequest(mapOf(\"error\" to filterResult.error, \"field\" to filterResult.field))") + w.close("}") + w.line("val whereOp = ${shortName}WhereOp(filterResult.predicates)") + w.line("var q = if (whereOp != null) ${readObj}.selectAll().where { whereOp } else ${readObj}.selectAll()") + w.open("if (sort != null) {") + w.line("val parsed = parse${shortName}Sort(sort)") + w.indented { w.line("?: return@transaction jsonBadRequest(mapOf(\"error\" to \"invalid_sort\", \"field\" to sort.substringBefore(':')))") } + w.line("val (field, dir) = parsed") + writeOrderBy(w, readObj, shortName, sortFields, api) + w.close("}") + w.line("val total: Long = if (withCount == \"1\") q.count() else -1L") + w.line("val effectiveLimit = requestedLimit ?: (maxRows + 1)") if (api == ExposedApi.V1) { - append(" val rows = q.limit(effectiveLimit).offset(effectiveOffset).map { rowTo${shortName}(it) }\n") + w.line("val rows = q.limit(effectiveLimit).offset(effectiveOffset).map { rowTo${shortName}(it) }") } else { - append(" val rows = q.limit(effectiveLimit, effectiveOffset).map { rowTo${shortName}(it) }\n") + w.line("val rows = q.limit(effectiveLimit, effectiveOffset).map { rowTo${shortName}(it) }") } - append(" if (requestedLimit == null && rows.size > maxRows) return@transaction jsonBadRequest($x.tooLarge())\n") + w.line("if (requestedLimit == null && rows.size > maxRows) return@transaction jsonBadRequest($x.tooLarge())") // #484: csv and xml name no credential column (the export's own FIELDS); the json body drops the key. val jsonRows = if (creds.isEmpty()) "rows" else "rows.map { redact$shortName(objectMapper, it) }" - append(" val ok = ResponseEntity.ok()\n") - append(" .header(\"Content-Disposition\", $x.contentDisposition(format))\n") - append(" .header(\"Content-Type\", $x.contentType(format))\n") - append(" when (format) {\n") - append(" \"csv\" -> ok.body($x.csv(rows) as Any)\n") - append(" \"xml\" -> ok.body($x.xml(rows) as Any)\n") - append(" else -> if (withCount == \"1\") ok.body(mapOf(\"rows\" to $jsonRows, \"total\" to total) as Any) else ok.body($jsonRows as Any)\n") - append(" }\n") - append(" }\n\n") - append(" private fun jsonBadRequest(body: Any): ResponseEntity =\n") - append(" ResponseEntity.badRequest().contentType(org.springframework.http.MediaType.APPLICATION_JSON).body(body)\n\n") - append(" private fun jsonOk(body: Any): ResponseEntity =\n") - append(" ResponseEntity.ok().contentType(org.springframework.http.MediaType.APPLICATION_JSON).body(body)\n\n") + w.line("val ok = ResponseEntity.ok()") + w.indented { + w.line(".header(\"Content-Disposition\", $x.contentDisposition(format))") + w.line(".header(\"Content-Type\", $x.contentType(format))") + } + w.open("when (format) {") + w.line("\"csv\" -> ok.body($x.csv(rows) as Any)") + w.line("\"xml\" -> ok.body($x.xml(rows) as Any)") + w.line("else -> if (withCount == \"1\") ok.body(mapOf(\"rows\" to $jsonRows, \"total\" to total) as Any) else ok.body($jsonRows as Any)") + w.close("}") + w.close("}").blank() + w.line("private fun jsonBadRequest(body: Any): ResponseEntity =") + w.indented { w.line("ResponseEntity.badRequest().contentType(org.springframework.http.MediaType.APPLICATION_JSON).body(body)") }.blank() + w.line("private fun jsonOk(body: Any): ResponseEntity =") + w.indented { w.line("ResponseEntity.ok().contentType(org.springframework.http.MediaType.APPLICATION_JSON).body(body)") }.blank() } /** GET /{id} — single row by primary key, 404 envelope on a miss. */ private fun appendGetHandler( - sb: StringBuilder, shortName: String, readObj: String, pkFieldName: String, pkParamType: String, + w: KotlinWriter, shortName: String, readObj: String, pkFieldName: String, pkParamType: String, creds: Collection = emptyList(), - ) = with(sb) { + ) { // GET /{id} - append(" @GetMapping(\"/{id}\")\n") - append(" fun get(@PathVariable id: $pkParamType): ResponseEntity = transaction {\n") - append(" val row = ${readObj}.selectAll().where { ${readObj}.${pkFieldName} eq id }.singleOrNull()\n") - append(" ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)\n") - append(" ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)\n") - append(" }\n\n") + w.line("@GetMapping(\"/{id}\")") + w.open("fun get(@PathVariable id: $pkParamType): ResponseEntity = transaction {") + w.line("val row = ${readObj}.selectAll().where { ${readObj}.${pkFieldName} eq id }.singleOrNull()") + w.indented { w.line("?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf(\"error\" to \"not_found\") as Any)") } + w.line("ResponseEntity.ok(${wireRow(shortName, creds, "row")} as Any)") + w.close("}").blank() } /** A single-field `identity.primary @generation: uuid` key — the one the create handler mints. */ @@ -2804,7 +2800,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase, @@ -2815,20 +2811,20 @@ private fun appendSortDefaultOrders( val v = f.getMetaAttr(MetaField.ATTR_SORTABLE_DEFAULT_ORDER).valueAsString if (v == "asc" || v == "desc") name to v else null } - sb.append("/** GENERATED — declared @sortableDefaultOrder per field for $shortName. */\n") + w.line("/** GENERATED — declared @sortableDefaultOrder per field for $shortName. */") // The type is STATED, not inferred. `mapOf()` with zero pairs leaves K and V with // nothing to resolve and Kotlin refuses to compile — and the common case is zero // pairs, because most models declare no @sortableDefaultOrder at all. A text-golden // snapshot cannot see this: it pins the emitted characters, and `mapOf(\n)` is a // perfectly ordinary-looking string. Only compiling the output catches it, which is // what the integration lane is for. - sb.append("private val ${shortName}SortDefaultOrder: Map = mapOf(\n") - for ((name, v) in declared) sb.append(" \"$name\" to \"$v\",\n") - sb.append(")\n\n") + w.open("private val ${shortName}SortDefaultOrder: Map = mapOf(") + for ((name, v) in declared) w.line("\"$name\" to \"$v\",") + w.close(")").blank() } /** - * The generated Kotlin expression resolving a sort FIELD NAME to its Exposed column. + * Writes the `q = q.orderBy(...)` statement whose `when` resolves a sort FIELD NAME to its Exposed column. * * Deliberately NOT `$table.columns.first { it.name == field }`. Exposed's `Column.name` is * the PHYSICAL SQL identifier — `created_at` under the default snake_case strategy — while @@ -2848,16 +2844,13 @@ private fun appendSortDefaultOrders( * `null` so a future divergence between the two surfaces a generator bug instead of * answering a valid request with a 400. */ -private fun sortColumnExpr(tableVar: String, shortName: String, sortFields: List, api: ExposedApi): String { - if (sortFields.isEmpty()) return "error(\"$shortName has no sortable fields\")" - val sb = StringBuilder("when (field) {\n") - for (name in sortFields) { - val prop = KotlinNaming.safeColumnProperty(name, api) - sb.append(" \"").append(name).append("\" -> ") - .append(tableVar).append(".").append(prop).append("\n") +private fun writeOrderBy(w: KotlinWriter, tableVar: String, shortName: String, sortFields: List, api: ExposedApi) { + if (sortFields.isEmpty()) { + w.line("q = q.orderBy(error(\"$shortName has no sortable fields\") to dir)") + return + } + w.block("q = q.orderBy(when (field) {", "} to dir)") { + for (name in sortFields) w.line("\"$name\" -> $tableVar.${KotlinNaming.safeColumnProperty(name, api)}") + w.line("else -> error(\"$shortName: sort field has no column (generator drift): \" + field)") } - sb.append(" else -> error(\"").append(shortName) - .append(": sort field has no column (generator drift): \" + field)\n") - sb.append(" }") - return sb.toString() } diff --git a/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json b/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json index 70369ff08..dfec060b3 100644 --- a/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json +++ b/server/java/codegen-kotlin/src/test/resources/layout-ratchet/allowlist.json @@ -8,7 +8,6 @@ "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt": "packageHeader() returns a package line with typed line breaks. No reference generator calls it since W-KT-2; it stays public for owned copies ejected at an earlier version, which still call it.", "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinPoetFileWriter.kt": "Lays its output out through KotlinPoet (the FileSpec-to-disk helper, retired when its last caller moves). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringConfigGenerator.kt": "Lays its output out through KotlinPoet (FileSpec for the Spring configuration class). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", - "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt": "Builds the Spring controller with typed line breaks and indentation throughout. Converted to KotlinWriter in W-KT-3.", "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt": "Lays its output out through KotlinPoet (TypeName values the entity and table generators share). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4." }, "exempt": { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorController.kt index e906092dd..7ed44c270 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorController.kt @@ -1,19 +1,27 @@ package acme.blog +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import jakarta.servlet.http.HttpServletRequest +import jakarta.validation.Validator +import java.io.ByteArrayOutputStream +import java.nio.charset.StandardCharsets +import java.sql.Timestamp +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.format.DateTimeFormatter import org.jetbrains.exposed.sql.Op -import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.ResultRow +import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.ObjectMapper -import jakarta.validation.Validator +import org.jetbrains.exposed.sql.update import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping @@ -26,14 +34,6 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController -import jakarta.servlet.http.HttpServletRequest -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets -import java.sql.Timestamp -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter /** GENERATED — sort allowlist for Author (cross-port API contract). */ private val AuthorSortAllowlist = setOf( @@ -287,7 +287,6 @@ private fun rowToAuthor(row: ResultRow): Author = Author( @RestController @RequestMapping("/api/authors") class AuthorController(private val objectMapper: ObjectMapper, private val validator: Validator) { - @GetMapping fun list( @RequestParam(required = false) limit: Int?, @@ -414,5 +413,4 @@ class AuthorController(private val objectMapper: ObjectMapper, private val valid val status = if (kind == "foreign_key" || kind == "unique") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST return ResponseEntity.status(status).body(mapOf("error" to "constraint_violation", "constraint" to kind) as Any) } - } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductController.kt index cb46c28ad..a20d64066 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/ProductController.kt @@ -1,19 +1,28 @@ package acme.catalog +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import jakarta.servlet.http.HttpServletRequest +import jakarta.validation.Validator +import java.io.ByteArrayOutputStream +import java.math.BigDecimal +import java.nio.charset.StandardCharsets +import java.sql.Timestamp +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.format.DateTimeFormatter import org.jetbrains.exposed.sql.Op -import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.ResultRow +import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.ObjectMapper -import jakarta.validation.Validator +import org.jetbrains.exposed.sql.update import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping @@ -26,15 +35,6 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController -import jakarta.servlet.http.HttpServletRequest -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets -import java.sql.Timestamp -import java.math.BigDecimal -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter /** GENERATED — sort allowlist for Product (cross-port API contract). */ private val ProductSortAllowlist = setOf( @@ -335,7 +335,6 @@ private fun rowToProduct(row: ResultRow): Product = Product( @RestController @RequestMapping("/api/products") class ProductController(private val objectMapper: ObjectMapper, private val validator: Validator) { - @GetMapping fun list( @RequestParam(required = false) limit: Int?, @@ -487,5 +486,4 @@ class ProductController(private val objectMapper: ObjectMapper, private val vali val status = if (kind == "foreign_key" || kind == "unique") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST return ResponseEntity.status(status).body(mapOf("error" to "constraint_violation", "constraint" to kind) as Any) } - } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductController.kt index cb46c28ad..a20d64066 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/ProductController.kt @@ -1,19 +1,28 @@ package acme.catalog +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import jakarta.servlet.http.HttpServletRequest +import jakarta.validation.Validator +import java.io.ByteArrayOutputStream +import java.math.BigDecimal +import java.nio.charset.StandardCharsets +import java.sql.Timestamp +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.format.DateTimeFormatter import org.jetbrains.exposed.sql.Op -import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.ResultRow +import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.ObjectMapper -import jakarta.validation.Validator +import org.jetbrains.exposed.sql.update import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping @@ -26,15 +35,6 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController -import jakarta.servlet.http.HttpServletRequest -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets -import java.sql.Timestamp -import java.math.BigDecimal -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter /** GENERATED — sort allowlist for Product (cross-port API contract). */ private val ProductSortAllowlist = setOf( @@ -335,7 +335,6 @@ private fun rowToProduct(row: ResultRow): Product = Product( @RestController @RequestMapping("/api/products") class ProductController(private val objectMapper: ObjectMapper, private val validator: Validator) { - @GetMapping fun list( @RequestParam(required = false) limit: Int?, @@ -487,5 +486,4 @@ class ProductController(private val objectMapper: ObjectMapper, private val vali val status = if (kind == "foreign_key" || kind == "unique") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST return ResponseEntity.status(status).body(mapOf("error" to "constraint_violation", "constraint" to kind) as Any) } - } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt index c713e990e..7b41ad490 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt @@ -1,19 +1,30 @@ package acme.auth +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import jakarta.servlet.http.HttpServletRequest +import jakarta.validation.Validator +import java.io.ByteArrayOutputStream +import java.math.BigDecimal +import java.nio.charset.StandardCharsets +import java.sql.Timestamp +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.format.DateTimeFormatter import org.jetbrains.exposed.sql.Op import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.SqlExpressionBuilder +import org.jetbrains.exposed.sql.TextColumnType import org.jetbrains.exposed.sql.and +import org.jetbrains.exposed.sql.castTo import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.ObjectMapper -import jakarta.validation.Validator +import org.jetbrains.exposed.sql.update import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping @@ -26,17 +37,6 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController -import jakarta.servlet.http.HttpServletRequest -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets -import java.sql.Timestamp -import java.math.BigDecimal -import org.jetbrains.exposed.sql.TextColumnType -import org.jetbrains.exposed.sql.castTo -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter /** GENERATED — sort allowlist for Auth (cross-port API contract). */ private val AuthSortAllowlist = setOf( @@ -346,7 +346,6 @@ private fun rowToAuth(row: ResultRow): Auth = Auth( @RestController @RequestMapping("/api/auths") class AuthController(private val objectMapper: ObjectMapper, private val validator: Validator) { - @GetMapping fun list( @RequestParam(required = false) limit: Int?, @@ -674,7 +673,6 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat else ResponseEntity.noContent().build() } - /** A request body that cannot be read is a client error naming the field, not a 500. */ @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException::class) fun handleUnreadableBody(e: org.springframework.http.converter.HttpMessageNotReadableException): ResponseEntity = @@ -704,5 +702,4 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat val status = if (kind == "foreign_key" || kind == "unique") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST return ResponseEntity.status(status).body(mapOf("error" to "constraint_violation", "constraint" to kind) as Any) } - } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineController.kt index 3e7c1c77f..3345b3387 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineController.kt @@ -1,19 +1,27 @@ package acme.auth +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import jakarta.servlet.http.HttpServletRequest +import jakarta.validation.Validator +import java.io.ByteArrayOutputStream +import java.nio.charset.StandardCharsets +import java.sql.Timestamp +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.format.DateTimeFormatter import org.jetbrains.exposed.sql.Op -import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.ResultRow +import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.ObjectMapper -import jakarta.validation.Validator +import org.jetbrains.exposed.sql.update import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping @@ -26,14 +34,6 @@ import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController -import jakarta.servlet.http.HttpServletRequest -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets -import java.sql.Timestamp -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter /** GENERATED — sort allowlist for AuthLine (cross-port API contract). */ private val AuthLineSortAllowlist = setOf( @@ -286,7 +286,6 @@ private fun rowToAuthLine(row: ResultRow): AuthLine = AuthLine( @RestController @RequestMapping("/api/auth_lines") class AuthLineController(private val objectMapper: ObjectMapper, private val validator: Validator) { - @GetMapping fun list( @RequestParam(required = false) limit: Int?, @@ -411,5 +410,4 @@ class AuthLineController(private val objectMapper: ObjectMapper, private val val val status = if (kind == "foreign_key" || kind == "unique") HttpStatus.CONFLICT else HttpStatus.BAD_REQUEST return ResponseEntity.status(status).body(mapOf("error" to "constraint_violation", "constraint" to kind) as Any) } - } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/SalesReportController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/SalesReportController.kt index a70627797..e9c810260 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/SalesReportController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-view/acme/report/SalesReportController.kt @@ -1,8 +1,16 @@ package acme.report +import jakarta.servlet.http.HttpServletRequest +import java.io.ByteArrayOutputStream +import java.nio.charset.StandardCharsets +import java.sql.Timestamp +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.format.DateTimeFormatter import org.jetbrains.exposed.sql.Op -import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.ResultRow +import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.selectAll @@ -14,14 +22,6 @@ import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController -import jakarta.servlet.http.HttpServletRequest -import java.io.ByteArrayOutputStream -import java.nio.charset.StandardCharsets -import java.sql.Timestamp -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.format.DateTimeFormatter /** GENERATED — sort allowlist for SalesReport (cross-port API contract). */ private val SalesReportSortAllowlist = setOf( @@ -285,7 +285,6 @@ private fun rowToSalesReport(row: ResultRow): SalesReport = SalesReport( @RestController @RequestMapping("/api/sales_reports") class SalesReportController { - @GetMapping fun list( @RequestParam(required = false) limit: Int?,