From 8d064e22d8d6651f451dc5840b8e7ff73f7b7d6d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 26 Nov 2026 05:08:39 -0500 Subject: [PATCH 1/3] feat(codegen-kotlin): move the Exposed tier onto KotlinWriter (W-KT-2) The Exposed table generator (the table object and its seven per-package support files), the relation helpers, the repository base and the extract mirror now write through KotlinWriter (ADR-0063) and no longer import KotlinPoet; they read the type mapper's KotlinPoet types by qualified name until W-KT-4 retires it. Their four entries leave the layout ratchet's allowlist. Generated output changes in layout only: sorted imports, no blank line at the start of a body or the end of a support file, a short parameter list on one line, a long KDoc as a block, a blank line after a header comment. The snapshot goldens are refreshed to match. KotlinWriter now imports a root-package name into a file in a named package, as the replaced generators did; a new kotlin writer case pins it. --- CHANGELOG.md | 15 + docs/CONFORMANCE.md | 2 +- .../cases/kotlin-imports-root-package.json | 25 + .../exposed1x/Exposed1xRoundTripTest.kt | 4 +- .../kotlin/KotlinExposedTableGenerator.kt | 1133 ++++++++--------- .../kotlin/KotlinExtractSchemaEmitter.kt | 147 +-- .../kotlin/KotlinRelationsGenerator.kt | 253 ++-- .../kotlin/KotlinRepositoryGenerator.kt | 307 ++--- .../generator/kotlin/writer/KotlinWriter.kt | 6 +- .../kotlin/KotlinExposedTableGeneratorTest.kt | 2 +- .../KotlinProjectionExtendsInheritanceTest.kt | 2 +- .../generator/kotlin/KotlinTypeMapperTest.kt | 2 +- .../resources/layout-ratchet/allowlist.json | 6 +- .../acme/events/EventRepositoryBase.kt | 3 +- .../acme/events/NoteRepositoryBase.kt | 3 +- .../acme/blog/PostTable.kt | 2 +- .../acme/blog/AuthorRepositoryBase.kt | 3 +- .../acme/catalog/MetaPortableColumnTypes.kt | 3 +- .../acme/catalog/MetaPortableColumnTypes.kt | 3 +- .../acme/blog/AuthorRepositoryBase.kt | 3 +- .../acme/blog/PostRepositoryBase.kt | 3 +- .../entity-with-fk/acme/blog/PostTable.kt | 2 +- .../acme/commerce/MetaJsonbMapper.kt | 1 - .../acme/commerce/MetaJsonbMapper.kt | 1 - .../acme/auth/AuthLineTable.kt | 2 +- .../acme/auth/MetaPortableColumnTypes.kt | 3 +- .../acme/demo/AuthorRepositoryBase.kt | 3 +- .../demo/MetaInstantWithTimeZoneColumnType.kt | 1 - .../acme/ai/OpinionOutputPayloadExtracted.kt | 7 +- .../acme/ai/GreetingExtracted.kt | 7 +- .../KotlinCodegenMatchesReferenceTest.kt | 2 +- .../integration/kotlin/tables/AssetTable.kt | 2 +- spec/code-writer.md | 4 +- 33 files changed, 960 insertions(+), 1002 deletions(-) create mode 100644 fixtures/writer-conformance/cases/kotlin-imports-root-package.json diff --git a/CHANGELOG.md b/CHANGELOG.md index de4afd796e..aa22da2332 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1637,6 +1637,21 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru ejected at an earlier version calls (each emitter's `write`, `BODY`, `body(wire)`, `KotlinNaming.packageHeader`) is kept. +- **The Kotlin Exposed tier writes through `KotlinWriter`** (ADR-0063): the Exposed table + generator (the `Table` object and its seven per-package support files: instant with + time zone, inet and uri, duration, int-backed enum array, portable decimal and uuid, uuid string + and the jsonb mapper), the relation helpers, the repository base and the extract mirror. None of + them imports KotlinPoet any more; they read the type mapper's KotlinPoet types by qualified name + until W-KT-4 retires it. **Their output changes in layout only:** imports in one sorted group, + no blank line at the start of a class or companion body, no blank line at the end of a support + file, a one-property extract mirror on one line, a KDoc too long for one line written as a block, + and a blank line after the extract mirror's header comment. `KotlinWriter` now imports a + root-package name (one with no dot) into a file in a named package, as the generators it + replaced did; a new `kotlin` writer case pins it. The support files' text builders + (`instantTzSupportBlock`, `inetUriSupportFileImports` and the rest) became writer functions + (`writeInstantTzSupport` and its siblings); 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/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index a99424e333..9ffe8164d7 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -71,7 +71,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | ✓ (every case but the three-way merge one) | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 86 cases (31 core + 10 TypeScript + 9 Java + 10 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 87 cases (31 core + 10 TypeScript + 9 Java + 11 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | — | diff --git a/fixtures/writer-conformance/cases/kotlin-imports-root-package.json b/fixtures/writer-conformance/cases/kotlin-imports-root-package.json new file mode 100644 index 0000000000..a544e25ba0 --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-imports-root-package.json @@ -0,0 +1,25 @@ +{ + "description": "A name with no dot is in the root package: a file in a named package imports it, a file in the root package does not.", + "dialect": "kotlin", + "ops": [ + [ + "use", + "RootTable" + ], + [ + "package", + "com.acme" + ], + [ + "line", + "val t = RootTable" + ] + ], + "expected": [ + "package com.acme", + "", + "import RootTable", + "", + "val t = RootTable" + ] +} diff --git a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xRoundTripTest.kt b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xRoundTripTest.kt index 4cc7d4a19a..2ed48aeb19 100644 --- a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xRoundTripTest.kt +++ b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xRoundTripTest.kt @@ -18,8 +18,8 @@ import org.junit.jupiter.api.Assumptions.assumeTrue * Issue #390 acceptance criterion: "the emitted custom column types round-trip through a real * JDBC read under 1.x." `Exposed1xCodegenCompileTest` proves the full fitness corpus COMPILES * against Exposed 1.3.x; this test proves the hand-rolled `Meta*ColumnType` support classes - * ([KotlinExposedTableGenerator]'s `instantTzSupportBlock` / `inetUriSupportBlock` / - * `uuidStringSupportBlock`) actually read back correctly against a real Postgres: + * ([KotlinExposedTableGenerator]'s `writeInstantTzSupport` / `writeInetUriSupport` / + * `writeUuidStringSupport`) actually read back correctly against a real Postgres: * * - `MetaInstantWithTimeZoneColumnType` (a `field.timestamp`, default/non-`@localTime`), * - `MetaUriColumnType` (`field.uri`), diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 7e409e8750..d52847b503 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -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.MetaData import com.metaobjects.database.ColumnNaming @@ -43,10 +44,8 @@ import com.metaobjects.reporting.ReportReadModel import com.metaobjects.reporting.ReportShape import com.metaobjects.source.MetaSource import com.metaobjects.source.RdbSource -import com.squareup.kotlinpoet.ClassName import java.io.OutputStream import java.io.PrintWriter -import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import org.slf4j.LoggerFactory @@ -334,10 +333,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase, val unsizedDecimals: Set) + private class ReportTablePlan(val enumClasses: Map, val unsizedDecimals: Set) /** * The plan of the report being emitted, keyed by its read model for the duration of @@ -569,7 +565,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase, entity: MetaObject): ClassName? = + private fun enumClassFor(field: MetaField<*>, entity: MetaObject): com.squareup.kotlinpoet.ClassName? = reportPlans[entity]?.enumClasses?.get(field.name) ?: KotlinTypeMapper.enumTypeName(field, entity, providedEnums) /** @@ -681,13 +677,13 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` column types ([durationSupportBlock]) and, beside it, the + * `Column` column types ([writeDurationSupport]) and, beside it, the * package's `MetaDurationWire.kt` they format and parse through. */ private fun emitDurationSupportFile(pkg: String, outRoot: Path) { KotlinDurationWireEmitter.write(pkg, outRoot) val api = exposedApi() - emitSupportFile(pkg, outRoot, DURATION_SUPPORT_FILE_NAME, durationSupportFileImports(api), durationSupportBlock(api)) + emitSupportFile(pkg, outRoot, DURATION_SUPPORT_FILE_NAME) { writeDurationSupport(it, api) } } private fun entityNeedsUuidStringHelper(entity: MetaObject, loader: MetaDataLoader): Boolean = @@ -708,7 +704,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase.kt`): a package header (when the - * package is non-empty), optional import lines, then the declaration block. Shared by the - * jsonb-mapper / inet-uri / instant-tz emitters, which differ only in file name, imports, and - * block — the `internal` declarations let every `*Table.kt` in the package reuse one copy. + * Emit one `internal` per-package support file (`.kt`): [write] records the imports + * and writes the declarations, and the writer lays out the package line and import block. + * Shared by every support-file emitter, which differ only in file name and contents — the + * `internal` declarations let every `*Table.kt` in the package reuse one copy. */ - private fun emitSupportFile(pkg: String, outRoot: Path, fileName: String, imports: String, block: String) { - val body = buildString { - if (pkg.isNotEmpty()) append("package $pkg\n\n") - if (imports.isNotEmpty()) { append(imports); append("\n") } - append(block) - append("\n") - } + private fun emitSupportFile(pkg: String, outRoot: Path, fileName: String, write: (KotlinWriter) -> Unit) { + val w = KotlinWriter().packageName(pkg) + write(w) val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$fileName.kt") - GeneratedFileWriter.write(outFile, body) + GeneratedFileWriter.write(outFile, w.toString()) } /** @@ -1054,7 +1043,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase naming) contribute no // import, so a single-package model's output stays byte-identical. val crossPackageEnumImports = sortedSetOf().apply { - fun consider(cn: ClassName?) { + fun consider(cn: com.squareup.kotlinpoet.ClassName?) { if (cn != null && cn.packageName.isNotEmpty() && cn.packageName != pkg) { add("${cn.packageName}.${cn.simpleName}") } @@ -1067,55 +1056,51 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` type is inferred). - append("\n") - if (isView) { - append("/** READ-ONLY VIEW — generated from view metadata; do not insert/update/delete directly. */\n") - } - append("/** GENERATED — do not hand-edit. Regenerated from metadata. */\n") - append("object $tableObjectName : Table($qualifiedTableExpr) {\n") + val w = KotlinWriter().packageName(pkg) + w.use(ExposedImports.core(api, "Table")) + if (declaresSequence) w.use(ExposedImports.core(api, "Sequence")) + if (fkColumns.any { it.hasReferenceOption } || needsRefOptForDecor) { + w.use(ExposedImports.core(api, "ReferenceOption")) + } + for (imp in columnFunctionImports) { + w.use(imp) + } + for (imp in crossPackageTableImports) { + w.use(imp) + } + for (imp in crossPackageEnumImports) { + w.use(imp) + } + if (needsJsonbExtensionImport) { + w.use(ExposedImports.json(api, "jsonb")) + } + // Only the open-bag `field.string @dbColumnType=jsonb` (JsonElement) uses kotlinx Json. + // Object/map jsonb columns use the same-package `metaJsonbMapper` (no import needed). + if (needsKotlinxJsonImport) { + w.use("kotlinx.serialization.json.Json") + } + // R6 Plan 2a: the gen_random_uuid() server default uses CustomFunction + + // UUIDColumnType, which need explicit imports (neither is a Table member). Under + // 1.x the java.util.UUID-binding UUIDColumnType moved to core.java (issue #390) — + // uuid PK generation always needs java.util.UUID, never kotlin.uuid.Uuid, so this + // is unconditional on [ExposedApi], not gated by whether the column itself is a + // `field.uuid` vs a `@dbColumnType=uuid` string. + if (uuidGeneratedPk) { + w.use(ExposedImports.core(api, "CustomFunction")) + val uuidColumnTypeImport = + if (api == ExposedApi.V1) ExposedImports.javaUuid("UUIDColumnType") + else ExposedImports.core(api, "UUIDColumnType") + w.use(uuidColumnTypeImport) + } + // an instant (default) timestamp calls the `instantWithTimeZone(...)` extension + // from the package-shared MetaInstantWithTimeZoneColumnType.kt support file. That + // extension is `internal` + same-package, so the table file needs NO import for it + // and NO Instant/Column imports (the column's `Column` type is inferred). + if (isView) { + w.doc("READ-ONLY VIEW — generated from view metadata; do not insert/update/delete directly.") + } + w.doc("GENERATED — do not hand-edit. Regenerated from metadata.") + w.block("object $tableObjectName : Table($qualifiedTableExpr) {") { // PK column(s) FIRST so a self-referential FK column (e.g. // `parentId = uuid(...).references(SelfTable.id)`) can reference the // PK `val id` — Kotlin object initializers run top-to-bottom, so a @@ -1187,7 +1172,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase", col1, ...) }` for identity.secondary // and `init { index("", false, col1, ...) }` for index.lookup, all @@ -1235,33 +1221,33 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` whose SQL DDL is `TIMESTAMP WITH TIME ZONE`. - | * Delegates all value/JDBC handling to Exposed's `JavaInstantColumnType` and - | * overrides only `sqlType()`, so the column type matches the `Instant` data-class - | * property (no Instant↔OffsetDateTime coercion) while staying timezone-aware. - | */ - |internal class MetaInstantWithTimeZoneColumnType : - | ColumnType(), - | IDateColumnType { - | private val delegate = JavaInstantColumnType() - | override val hasTimePart: Boolean get() = delegate.hasTimePart - | override fun sqlType(): String = - | currentDialect.dataTypeProvider.timestampWithTimeZoneType() - | override fun valueFromDB(value: Any): Instant? = delegate.valueFromDB(value) - | override fun notNullValueToDB(value: Instant): Any = delegate.notNullValueToDB(value) - | override fun nonNullValueToString(value: Instant): String = delegate.nonNullValueToString(value) - | override fun nonNullValueAsDefaultString(value: Instant): String = - | delegate.nonNullValueAsDefaultString(value) - | override fun readObject(rs: $readObjectParamType, index: Int): Any? = delegate.readObject(rs, index) - | override fun setParameter( - | stmt: PreparedStatementApi, - | index: Int, - | value: Any?, - | ) = delegate.setParameter(stmt, index, value) - |} - | - |/** - | * Column builder for instant (default, non-`@localTime`): a `Column` backed by - | * a `TIMESTAMP WITH TIME ZONE` Postgres column (see [MetaInstantWithTimeZoneColumnType]). - | */ - |internal fun Table.instantWithTimeZone(name: String): Column = - | registerColumn(name, MetaInstantWithTimeZoneColumnType()) - |""".trimMargin() + w.text( + """ + /** + * GENERATED — do not hand-edit. + * Custom Exposed column type for instant (default, non-`@localTime`): a + * `Column` whose SQL DDL is `TIMESTAMP WITH TIME ZONE`. + * Delegates all value/JDBC handling to Exposed's `JavaInstantColumnType` and + * overrides only `sqlType()`, so the column type matches the `Instant` data-class + * property (no Instant↔OffsetDateTime coercion) while staying timezone-aware. + */ + internal class MetaInstantWithTimeZoneColumnType : + ColumnType(), + IDateColumnType { + private val delegate = JavaInstantColumnType() + override val hasTimePart: Boolean get() = delegate.hasTimePart + override fun sqlType(): String = + currentDialect.dataTypeProvider.timestampWithTimeZoneType() + override fun valueFromDB(value: Any): Instant? = delegate.valueFromDB(value) + override fun notNullValueToDB(value: Instant): Any = delegate.notNullValueToDB(value) + override fun nonNullValueToString(value: Instant): String = delegate.nonNullValueToString(value) + override fun nonNullValueAsDefaultString(value: Instant): String = + delegate.nonNullValueAsDefaultString(value) + override fun readObject(rs: $readObjectParamType, index: Int): Any? = delegate.readObject(rs, index) + override fun setParameter( + stmt: PreparedStatementApi, + index: Int, + value: Any?, + ) = delegate.setParameter(stmt, index, value) + } + + /** + * Column builder for instant (default, non-`@localTime`): a `Column` backed by + * a `TIMESTAMP WITH TIME ZONE` Postgres column (see [MetaInstantWithTimeZoneColumnType]). + */ + internal fun Table.instantWithTimeZone(name: String): Column = + registerColumn(name, MetaInstantWithTimeZoneColumnType()) + """ + ) } /** @@ -1746,32 +1715,6 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` whose SQL DDL + * is plain `text` (Postgres has no uri type). The native URI binding matches the data + * class property; the value persists as its string form. + */ + internal class MetaUriColumnType : ColumnType() { + override fun sqlType(): String = currentDialect.dataTypeProvider.textType() + override fun valueFromDB(value: Any): URI = when (value) { + is URI -> value + else -> URI.create(value.toString()) + } + override fun notNullValueToDB(value: URI): Any = value.toString() + override fun nonNullValueToString(value: URI): String = "'${'$'}value'" + } + + /** Column builder for `field.uri`: a `Column` over a `text` column. */ + internal fun Table.uriColumn(name: String): Column = + registerColumn(name, MetaUriColumnType()) + + /** + * GENERATED — do not hand-edit. + * Custom Exposed column type for `field.inet`: a `Column` whose + * SQL DDL is the Postgres-native `inet`. The native InetAddress binding matches the data + * class property; the value binds/reads as its host-literal string. + */ + internal class MetaInetColumnType : ColumnType() { + override fun sqlType(): String = "inet" + override fun valueFromDB(value: Any): InetAddress = when (value) { + is InetAddress -> value + else -> InetAddress.getByName(value.toString()) + } + override fun notNullValueToDB(value: InetAddress): Any = value.hostAddress + override fun nonNullValueToString(value: InetAddress): String = "'${'$'}{value.hostAddress}'" + override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { + """ + ) // `setParameter`'s `value` has ALREADY been through `notNullValueToDB` by the time // `fillParameters`'s default implementation calls here (confirmed by decompiling it: // it calls `columnType.valueToDB(value)` — which for a non-null value delegates to @@ -1813,86 +1806,44 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` whose SQL DDL - | * is plain `text` (Postgres has no uri type). The native URI binding matches the data - | * class property; the value persists as its string form. - | */ - |internal class MetaUriColumnType : ColumnType() { - | override fun sqlType(): String = currentDialect.dataTypeProvider.textType() - | override fun valueFromDB(value: Any): URI = when (value) { - | is URI -> value - | else -> URI.create(value.toString()) - | } - | override fun notNullValueToDB(value: URI): Any = value.toString() - | override fun nonNullValueToString(value: URI): String = "'${'$'}value'" - |} - | - |/** Column builder for `field.uri`: a `Column` over a `text` column. */ - |internal fun Table.uriColumn(name: String): Column = - | registerColumn(name, MetaUriColumnType()) - | - |/** - | * GENERATED — do not hand-edit. - | * Custom Exposed column type for `field.inet`: a `Column` whose - | * SQL DDL is the Postgres-native `inet`. The native InetAddress binding matches the data - | * class property; the value binds/reads as its host-literal string. - | */ - |internal class MetaInetColumnType : ColumnType() { - | override fun sqlType(): String = "inet" - | override fun valueFromDB(value: Any): InetAddress = when (value) { - | is InetAddress -> value - | else -> InetAddress.getByName(value.toString()) - | } - | override fun notNullValueToDB(value: InetAddress): Any = value.hostAddress - | override fun nonNullValueToString(value: InetAddress): String = "'${'$'}{value.hostAddress}'" - | override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { - |${inetSetParameterBlock} - |} - | - |/** Column builder for `field.inet`: a `Column` over an `inet` column. */ - |internal fun Table.inetColumn(name: String): Column = - | registerColumn(name, MetaInetColumnType()) - |""".trimMargin() + w.text( + """ + } + + /** Column builder for `field.inet`: a `Column` over an `inet` column. */ + internal fun Table.inetColumn(name: String): Column = + registerColumn(name, MetaInetColumnType()) + """ + ) } /** File name (sans `.kt`) of the per-package support file for `field.duration` columns. */ const val DURATION_SUPPORT_FILE_NAME = "MetaDurationColumnType" - /** Imports for [durationSupportBlock], keyed by [ExposedApi] (1.x binds an array through the raw statement). */ - fun durationSupportFileImports(api: ExposedApi): String = """ - |import java.time.Duration - |import ${ExposedImports.core(api, "Column")} - |import ${ExposedImports.core(api, "ColumnType")} - |import ${ExposedImports.core(api, "Table")} - |import ${ExposedImports.statementsApi(api, "PreparedStatementApi")} - |import ${ExposedImports.vendors(api, "currentDialect")} - |${if (api == ExposedApi.V1) "import org.jetbrains.exposed.v1.jdbc.statements.jdbc.JdbcPreparedStatementImpl" else ""} - |""".trimMargin().replace("\n\n", "\n").trimEnd() + "\n" - /** * Shared support body for [DURATION_SUPPORT_FILE_NAME].kt — the `field.duration` columns: * @@ -1908,182 +1859,156 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase value + is Number -> MetaDurationWire.fromMicros(value.toLong()) + else -> MetaDurationWire.fromStored(value.toString()) + } + + /** + * GENERATED — do not hand-edit. A `java.time.Duration` column: native `INTERVAL` on Postgres, and + * elsewhere a BIGINT count of microseconds, so a range filter and a sort order it as a number. + */ + internal class MetaDurationColumnType : ColumnType() { + override fun sqlType(): String = if (isPostgres()) "INTERVAL" else "BIGINT" + override fun valueFromDB(value: Any): Duration = durationOf(value) + override fun notNullValueToDB(value: Duration): Any = stored(value) + override fun nonNullValueToString(value: Duration): String = + if (isPostgres()) "'" + stored(value) + "'" else stored(value).toString() + // The value binds as text; Postgres will not take a varchar where an interval goes, so the + // marker casts it (an explicit cast from text to interval is always allowed). + override fun parameterMarker(value: Duration?): String = if (isPostgres()) "CAST(? AS INTERVAL)" else "?" + } + + /** Column builder for `field.duration`: a `Column`. */ + internal fun Table.durationColumn(name: String): Column = + registerColumn(name, MetaDurationColumnType()) + + /** + * GENERATED — do not hand-edit. An `isArray` duration column: `INTERVAL[]` on Postgres, and elsewhere + * a JSON text array of microsecond counts. + */ + internal class MetaDurationArrayColumnType : ColumnType>() { + private fun element(value: Any): Duration = durationOf(value) + private fun json(value: List): String = value.joinToString(",", "[", "]") { MetaDurationWire.toMicros(it).toString() } + override fun sqlType(): String = if (isPostgres()) "INTERVAL[]" else if (isMySql()) "JSON" else "TEXT" + override fun valueFromDB(value: Any): List = when (value) { + is java.sql.Array -> (value.array as Array<*>).map { element(it!!) } + is Array<*> -> value.map { element(it!!) } + is List<*> -> value.map { element(it!!) } + else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { + if (it.isIntegralNumber) MetaDurationWire.fromMicros(it.longValue()) else MetaDurationWire.fromNode(it) + } + } + override fun notNullValueToDB(value: List): Any = + if (isPostgres()) value.map { MetaDurationWire.formatPostgres(it) }.toTypedArray() else json(value) + override fun nonNullValueToString(value: List): String = + if (isPostgres()) value.joinToString(",", "ARRAY[", "]::interval[]") { "'" + MetaDurationWire.formatPostgres(it) + "'" } + else "'" + json(value) + "'" + override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { + if (value is Array<*>) { + """ + ) // 0.x binds a typed array by element-type name; 1.x wants an ArrayColumnType there, so it // binds through the raw JDBC statement, as MetaDecimalArrayColumnType does. - val arrayBind = if (api == ExposedApi.V1) { - " @Suppress(\"UNCHECKED_CAST\")\n" + - " val raw = (stmt as JdbcPreparedStatementImpl).statement\n" + - " raw.setArray(index, raw.connection.createArrayOf(\"interval\", value as Array))" - } else { - " @Suppress(\"UNCHECKED_CAST\")\n" + - " stmt.setArray(index, \"interval\", value as Array)" - } - return """ - |private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) - | - |private fun isMySql(): Boolean = currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } - | - |/** The stored form of a duration: the interval spelling on Postgres, a 64-bit microsecond count elsewhere. */ - |private fun stored(value: Duration): Any = - | if (isPostgres()) MetaDurationWire.formatPostgres(value) else MetaDurationWire.toMicros(value) - | - |/** A stored value: a microsecond count (SQLite, MySQL), or interval / ISO text. */ - |private fun durationOf(value: Any): Duration = when (value) { - | is Duration -> value - | is Number -> MetaDurationWire.fromMicros(value.toLong()) - | else -> MetaDurationWire.fromStored(value.toString()) - |} - | - |/** - | * GENERATED — do not hand-edit. A `java.time.Duration` column: native `INTERVAL` on Postgres, and - | * elsewhere a BIGINT count of microseconds, so a range filter and a sort order it as a number. - | */ - |internal class MetaDurationColumnType : ColumnType() { - | override fun sqlType(): String = if (isPostgres()) "INTERVAL" else "BIGINT" - | override fun valueFromDB(value: Any): Duration = durationOf(value) - | override fun notNullValueToDB(value: Duration): Any = stored(value) - | override fun nonNullValueToString(value: Duration): String = - | if (isPostgres()) "'" + stored(value) + "'" else stored(value).toString() - | // The value binds as text; Postgres will not take a varchar where an interval goes, so the - | // marker casts it (an explicit cast from text to interval is always allowed). - | override fun parameterMarker(value: Duration?): String = if (isPostgres()) "CAST(? AS INTERVAL)" else "?" - |} - | - |/** Column builder for `field.duration`: a `Column`. */ - |internal fun Table.durationColumn(name: String): Column = - | registerColumn(name, MetaDurationColumnType()) - | - |/** - | * GENERATED — do not hand-edit. An `isArray` duration column: `INTERVAL[]` on Postgres, and elsewhere - | * a JSON text array of microsecond counts. - | */ - |internal class MetaDurationArrayColumnType : ColumnType>() { - | private fun element(value: Any): Duration = durationOf(value) - | private fun json(value: List): String = value.joinToString(",", "[", "]") { MetaDurationWire.toMicros(it).toString() } - | override fun sqlType(): String = if (isPostgres()) "INTERVAL[]" else if (isMySql()) "JSON" else "TEXT" - | override fun valueFromDB(value: Any): List = when (value) { - | is java.sql.Array -> (value.array as Array<*>).map { element(it!!) } - | is Array<*> -> value.map { element(it!!) } - | is List<*> -> value.map { element(it!!) } - | else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { - | if (it.isIntegralNumber) MetaDurationWire.fromMicros(it.longValue()) else MetaDurationWire.fromNode(it) - | } - | } - | override fun notNullValueToDB(value: List): Any = - | if (isPostgres()) value.map { MetaDurationWire.formatPostgres(it) }.toTypedArray() else json(value) - | override fun nonNullValueToString(value: List): String = - | if (isPostgres()) value.joinToString(",", "ARRAY[", "]::interval[]") { "'" + MetaDurationWire.formatPostgres(it) + "'" } - | else "'" + json(value) + "'" - | override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { - | if (value is Array<*>) { - |$arrayBind - | } else { - | super.setParameter(stmt, index, value) - | } - | } - |} - | - |/** Column builder for an `isArray` `field.duration`: a `Column>`. */ - |internal fun Table.durationArrayColumn(name: String): Column> = - | registerColumn(name, MetaDurationArrayColumnType()) - |""".trimMargin() + writeArrayBind(w, api, "interval") + w.text( + """ + } else { + super.setParameter(stmt, index, value) + } + } + } + + /** Column builder for an `isArray` `field.duration`: a `Column>`. */ + internal fun Table.durationArrayColumn(name: String): Column> = + registerColumn(name, MetaDurationArrayColumnType()) + """ + ) } /** File name (sans `.kt`) of the per-package support file for int-backed `field.enum` array columns. */ const val INT_ENUM_ARRAY_SUPPORT_FILE_NAME = "MetaIntEnumArrayColumnType" - /** Imports for [intEnumArraySupportBlock], keyed by [ExposedApi] (1.x binds an array through the raw statement). */ - fun intEnumArraySupportFileImports(api: ExposedApi): String = """ - |import ${ExposedImports.core(api, "Column")} - |import ${ExposedImports.core(api, "ColumnType")} - |import ${ExposedImports.core(api, "Table")} - |import ${ExposedImports.statementsApi(api, "PreparedStatementApi")} - |import ${ExposedImports.vendors(api, "currentDialect")} - |${if (api == ExposedApi.V1) "import org.jetbrains.exposed.v1.jdbc.statements.jdbc.JdbcPreparedStatementImpl" else ""} - |""".trimMargin().replace("\n\n", "\n").trimEnd() + "\n" - /** * Shared support body for [INT_ENUM_ARRAY_SUPPORT_FILE_NAME].kt: the column type of an int-backed * `isArray` `field.enum`. 0.x binds a typed array by element-type name; 1.x wants an * `ArrayColumnType` there, so it binds through the raw JDBC statement, as the other array types do. */ - fun intEnumArraySupportBlock(api: ExposedApi): String { - val intArrayBind = if (api == ExposedApi.V1) { - " @Suppress(\"UNCHECKED_CAST\")\n" + - " val raw = (stmt as JdbcPreparedStatementImpl).statement\n" + - " raw.setArray(index, raw.connection.createArrayOf(\"integer\", value as Array))" - } else { - " @Suppress(\"UNCHECKED_CAST\")\n" + - " stmt.setArray(index, \"integer\", value as Array)" - } - return """ - |private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) - | - |private fun isMySql(): Boolean = currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } - | - |/** - | * GENERATED — do not hand-edit. An int-backed `isArray` `field.enum` column: each member is stored as - | * its declared integer, in a native `INTEGER[]` on Postgres and elsewhere (no array type) a JSON text - | * array of numbers. [toInt] and [fromInt] are the enum's symbol↔integer mapping, generated as `when` - | * expressions; an integer with no member fails the read rather than inventing one. - | */ - |internal class MetaIntEnumArrayColumnType( - | private val toInt: (E) -> Int, - | private val fromInt: (Int) -> E, - |) : ColumnType>() { - | private fun json(value: List): String = value.joinToString(",", "[", "]") { toInt(it).toString() } - | override fun sqlType(): String = if (isPostgres()) "INTEGER[]" else if (isMySql()) "JSON" else "TEXT" - | override fun valueFromDB(value: Any): List = when (value) { - | is java.sql.Array -> (value.array as Array<*>).map { fromInt((it as Number).toInt()) } - | is Array<*> -> value.map { fromInt((it as Number).toInt()) } - | is List<*> -> value.map { fromInt((it as Number).toInt()) } - | else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { fromInt(it.intValue()) } - | } - | override fun notNullValueToDB(value: List): Any = - | if (isPostgres()) value.map { toInt(it) }.toTypedArray() else json(value) - | override fun nonNullValueToString(value: List): String = - | if (isPostgres()) value.joinToString(",", "ARRAY[", "]::integer[]") { toInt(it).toString() } else "'" + json(value) + "'" - | override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { - | if (value is Array<*>) { - |$intArrayBind - | } else { - | super.setParameter(stmt, index, value) - | } - | } - |} - | - |/** Column builder for an int-backed `isArray` `field.enum`: a `Column>`. */ - |internal fun Table.portableIntEnumArray(name: String, toInt: (E) -> Int, fromInt: (Int) -> E): Column> = - | registerColumn(name, MetaIntEnumArrayColumnType(toInt, fromInt)) - |""".trimMargin() + fun writeIntEnumArraySupport(w: KotlinWriter, api: ExposedApi) { + for (name in listOf("Column", "ColumnType", "Table")) w.use(ExposedImports.core(api, name)) + w.use(ExposedImports.statementsApi(api, "PreparedStatementApi")) + w.use(ExposedImports.vendors(api, "currentDialect")) + if (api == ExposedApi.V1) w.use("org.jetbrains.exposed.v1.jdbc.statements.jdbc.JdbcPreparedStatementImpl") + w.text( + """ + private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) + + private fun isMySql(): Boolean = currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } + + /** + * GENERATED — do not hand-edit. An int-backed `isArray` `field.enum` column: each member is stored as + * its declared integer, in a native `INTEGER[]` on Postgres and elsewhere (no array type) a JSON text + * array of numbers. [toInt] and [fromInt] are the enum's symbol↔integer mapping, generated as `when` + * expressions; an integer with no member fails the read rather than inventing one. + */ + internal class MetaIntEnumArrayColumnType( + private val toInt: (E) -> Int, + private val fromInt: (Int) -> E, + ) : ColumnType>() { + private fun json(value: List): String = value.joinToString(",", "[", "]") { toInt(it).toString() } + override fun sqlType(): String = if (isPostgres()) "INTEGER[]" else if (isMySql()) "JSON" else "TEXT" + override fun valueFromDB(value: Any): List = when (value) { + is java.sql.Array -> (value.array as Array<*>).map { fromInt((it as Number).toInt()) } + is Array<*> -> value.map { fromInt((it as Number).toInt()) } + is List<*> -> value.map { fromInt((it as Number).toInt()) } + else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { fromInt(it.intValue()) } + } + override fun notNullValueToDB(value: List): Any = + if (isPostgres()) value.map { toInt(it) }.toTypedArray() else json(value) + override fun nonNullValueToString(value: List): String = + if (isPostgres()) value.joinToString(",", "ARRAY[", "]::integer[]") { toInt(it).toString() } else "'" + json(value) + "'" + override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { + if (value is Array<*>) { + """ + ) + writeArrayBind(w, api, "integer") + w.text( + """ + } else { + super.setParameter(stmt, index, value) + } + } + } + + /** Column builder for an int-backed `isArray` `field.enum`: a `Column>`. */ + internal fun Table.portableIntEnumArray(name: String, toInt: (E) -> Int, fromInt: (Int) -> E): Column> = + registerColumn(name, MetaIntEnumArrayColumnType(toInt, fromInt)) + """ + ) } /** File name (sans `.kt`) of the per-package support file for `field.uuid` and `field.decimal` columns. */ const val PORTABLE_SUPPORT_FILE_NAME = "MetaPortableColumnTypes" - /** - * Imports for [portableSupportBlock]. 1.x's bare `UUIDColumnType` binds `kotlin.uuid.Uuid`, so - * the `java.util.UUID`-backed one comes from `core.java` (the substitution [uuidStringSupportFileImports] makes). - */ - fun portableSupportFileImports(api: ExposedApi): String { - val uuidColumnTypeImport = - if (api == ExposedApi.V1) ExposedImports.javaUuid("UUIDColumnType") - else ExposedImports.core(api, "UUIDColumnType") - return """ - |import java.math.BigDecimal - |import java.util.UUID - |import ${ExposedImports.core(api, "Column")} - |import ${ExposedImports.core(api, "ColumnType")} - |import ${ExposedImports.core(api, "DecimalColumnType")} - |import ${ExposedImports.core(api, "Table")} - |import ${ExposedImports.statementsApi(api, "PreparedStatementApi")} - |import $uuidColumnTypeImport - |import ${ExposedImports.vendors(api, "currentDialect")} - |${if (api == ExposedApi.V1) "import org.jetbrains.exposed.v1.jdbc.statements.jdbc.JdbcPreparedStatementImpl" else ""} - |""".trimMargin().replace("\n\n", "\n").trimEnd() + "\n" - } - /** * Shared support body for [PORTABLE_SUPPORT_FILE_NAME].kt. Exposed binds its `uuid()` as * 16 raw bytes on MySQL and SQLite, whose schemas (and the other ports) store a uuid as @@ -2092,111 +2017,137 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase))" - } else { - " @Suppress(\"UNCHECKED_CAST\")\n" + - " stmt.setArray(index, \"numeric\", value as Array)" + fun writePortableSupport(w: KotlinWriter, api: ExposedApi) { + // Imports. 1.x's bare `UUIDColumnType` binds `kotlin.uuid.Uuid`, so + // the `java.util.UUID`-backed one comes from `core.java` (the substitution [writeUuidStringSupport] makes). + w.use("java.math.BigDecimal") + w.use("java.util.UUID") + for (name in listOf("Column", "ColumnType", "DecimalColumnType", "Table")) w.use(ExposedImports.core(api, name)) + w.use(ExposedImports.statementsApi(api, "PreparedStatementApi")) + w.use(if (api == ExposedApi.V1) ExposedImports.javaUuid("UUIDColumnType") else ExposedImports.core(api, "UUIDColumnType")) + w.use(ExposedImports.vendors(api, "currentDialect")) + if (api == ExposedApi.V1) w.use("org.jetbrains.exposed.v1.jdbc.statements.jdbc.JdbcPreparedStatementImpl") + w.text( + """ + private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) + + private fun isSqlite(): Boolean = currentDialect.name.equals("sqlite", ignoreCase = true) + + /** GENERATED — do not hand-edit. A `java.util.UUID` column: native `uuid` on Postgres, text elsewhere. */ + internal class MetaPortableUuidColumnType : ColumnType() { + private val delegate = UUIDColumnType() + override fun sqlType(): String = delegate.sqlType() + override fun valueFromDB(value: Any): UUID = requireNotNull(delegate.valueFromDB(value)) { "null uuid column value" } + override fun notNullValueToDB(value: UUID): Any = + if (isPostgres()) delegate.notNullValueToDB(value) else value.toString() + override fun nonNullValueToString(value: UUID): String = + if (isPostgres()) delegate.nonNullValueToString(value) else "'${'$'}value'" + } + + /** Column builder for `field.uuid`: a `Column`. */ + internal fun Table.portableUuid(name: String): Column = + registerColumn(name, MetaPortableUuidColumnType()) + + /** GENERATED — do not hand-edit. A decimal column: the exact decimal everywhere but SQLite, which gets a REAL. */ + internal class MetaPortableDecimalColumnType(precision: Int, scale: Int) : ColumnType() { + private val delegate = DecimalColumnType(precision, scale) + override fun sqlType(): String = delegate.sqlType() + // ADR-0019 Amendment 1 (W4): SQLite stores a REAL, so a value is read at 15 significant + // digits, which turns `sum(0.1, 0.2)` (0.30000000000000004) back into 0.3. + override fun valueFromDB(value: Any): BigDecimal = + if (isSqlite() && value is Number && value !is BigDecimal) { + MetaDecimalWire.fromDouble15(value.toDouble()) + } else { + delegate.valueFromDB(value) + } + override fun notNullValueToDB(value: BigDecimal): Any = + if (isSqlite()) value.toDouble() else delegate.notNullValueToDB(value) + override fun nonNullValueToString(value: BigDecimal): String = delegate.nonNullValueToString(value) + } + + /** Column builder for `field.decimal`: a `Column`. */ + internal fun Table.portableDecimal(name: String, precision: Int, scale: Int): Column = + registerColumn(name, MetaPortableDecimalColumnType(precision, scale)) + + /** + * GENERATED — do not hand-edit. A decimal column with no declared `@precision`: plain unbounded + * `NUMERIC`, read exactly. Exposed's own `DecimalColumnType` would round every value to its scale + * (HALF_EVEN) on read, so this type does not delegate the read to it. + */ + internal class MetaUnboundedDecimalColumnType : ColumnType() { + override fun sqlType(): String = "NUMERIC" + override fun valueFromDB(value: Any): BigDecimal = when { + value is BigDecimal -> value + value is Number && isSqlite() -> MetaDecimalWire.fromDouble15(value.toDouble()) + else -> BigDecimal(value.toString()) + } + override fun notNullValueToDB(value: BigDecimal): Any = + if (isSqlite()) value.toDouble() else value + override fun nonNullValueToString(value: BigDecimal): String = value.toPlainString() + } + + /** Column builder for a `field.decimal` with no `@precision`: a `Column`, unbounded. */ + internal fun Table.portableDecimal(name: String): Column = + registerColumn(name, MetaUnboundedDecimalColumnType()) + + /** + * GENERATED — do not hand-edit. An `isArray` decimal column: a native `NUMERIC[]` on Postgres, and on + * MySQL and SQLite (no array type) a JSON text array of canonical strings. Elements are read exactly. + */ + internal class MetaDecimalArrayColumnType : ColumnType>() { + private fun isMySql(): Boolean = currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } + private fun decimalOf(element: Any): BigDecimal = if (element is BigDecimal) element else BigDecimal(element.toString()) + private fun json(value: List): String = value.joinToString(",", "[", "]") { "\"" + MetaDecimalWire.format(it) + "\"" } + override fun sqlType(): String = if (isPostgres()) "NUMERIC[]" else if (isMySql()) "JSON" else "TEXT" + override fun valueFromDB(value: Any): List = when (value) { + is java.sql.Array -> (value.array as Array<*>).map { decimalOf(it!!) } + is Array<*> -> value.map { decimalOf(it!!) } + is List<*> -> value.map { decimalOf(it!!) } + else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { MetaDecimalWire.fromNode(it) } + } + override fun notNullValueToDB(value: List): Any = + if (isPostgres()) value.toTypedArray() else json(value) + override fun nonNullValueToString(value: List): String = + if (isPostgres()) value.joinToString(",", "ARRAY[", "]::numeric[]") { it.toPlainString() } else "'" + json(value) + "'" + override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { + if (value is Array<*>) { + """ + ) + writeArrayBind(w, api, "numeric") + w.text( + """ + } else { + super.setParameter(stmt, index, value) + } + } + } + + /** Column builder for an `isArray` `field.decimal`: a `Column>`. */ + internal fun Table.portableDecimalArray(name: String): Column> = + registerColumn(name, MetaDecimalArrayColumnType()) + """ + ) + } + + /** + * The array branch of a support column type's `setParameter`, three levels in: 0.x binds a + * typed array by element-type name; 1.x wants an `ArrayColumnType` there, so it binds through + * the raw JDBC statement. + */ + private fun writeArrayBind(w: KotlinWriter, api: ExposedApi, sqlElementType: String) { + w.indented { + w.indented { + w.indented { + w.line("@Suppress(\"UNCHECKED_CAST\")") + if (api == ExposedApi.V1) { + w.line("val raw = (stmt as JdbcPreparedStatementImpl).statement") + w.line("raw.setArray(index, raw.connection.createArrayOf(\"$sqlElementType\", value as Array))") + } else { + w.line("stmt.setArray(index, \"$sqlElementType\", value as Array)") + } + } + } } - return """ - |private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) - | - |private fun isSqlite(): Boolean = currentDialect.name.equals("sqlite", ignoreCase = true) - | - |/** GENERATED — do not hand-edit. A `java.util.UUID` column: native `uuid` on Postgres, text elsewhere. */ - |internal class MetaPortableUuidColumnType : ColumnType() { - | private val delegate = UUIDColumnType() - | override fun sqlType(): String = delegate.sqlType() - | override fun valueFromDB(value: Any): UUID = requireNotNull(delegate.valueFromDB(value)) { "null uuid column value" } - | override fun notNullValueToDB(value: UUID): Any = - | if (isPostgres()) delegate.notNullValueToDB(value) else value.toString() - | override fun nonNullValueToString(value: UUID): String = - | if (isPostgres()) delegate.nonNullValueToString(value) else "'${'$'}value'" - |} - | - |/** Column builder for `field.uuid`: a `Column`. */ - |internal fun Table.portableUuid(name: String): Column = - | registerColumn(name, MetaPortableUuidColumnType()) - | - |/** GENERATED — do not hand-edit. A decimal column: the exact decimal everywhere but SQLite, which gets a REAL. */ - |internal class MetaPortableDecimalColumnType(precision: Int, scale: Int) : ColumnType() { - | private val delegate = DecimalColumnType(precision, scale) - | override fun sqlType(): String = delegate.sqlType() - | // ADR-0019 Amendment 1 (W4): SQLite stores a REAL, so a value is read at 15 significant - | // digits, which turns `sum(0.1, 0.2)` (0.30000000000000004) back into 0.3. - | override fun valueFromDB(value: Any): BigDecimal = - | if (isSqlite() && value is Number && value !is BigDecimal) { - | MetaDecimalWire.fromDouble15(value.toDouble()) - | } else { - | delegate.valueFromDB(value) - | } - | override fun notNullValueToDB(value: BigDecimal): Any = - | if (isSqlite()) value.toDouble() else delegate.notNullValueToDB(value) - | override fun nonNullValueToString(value: BigDecimal): String = delegate.nonNullValueToString(value) - |} - | - |/** Column builder for `field.decimal`: a `Column`. */ - |internal fun Table.portableDecimal(name: String, precision: Int, scale: Int): Column = - | registerColumn(name, MetaPortableDecimalColumnType(precision, scale)) - | - |/** - | * GENERATED — do not hand-edit. A decimal column with no declared `@precision`: plain unbounded - | * `NUMERIC`, read exactly. Exposed's own `DecimalColumnType` would round every value to its scale - | * (HALF_EVEN) on read, so this type does not delegate the read to it. - | */ - |internal class MetaUnboundedDecimalColumnType : ColumnType() { - | override fun sqlType(): String = "NUMERIC" - | override fun valueFromDB(value: Any): BigDecimal = when { - | value is BigDecimal -> value - | value is Number && isSqlite() -> MetaDecimalWire.fromDouble15(value.toDouble()) - | else -> BigDecimal(value.toString()) - | } - | override fun notNullValueToDB(value: BigDecimal): Any = - | if (isSqlite()) value.toDouble() else value - | override fun nonNullValueToString(value: BigDecimal): String = value.toPlainString() - |} - | - |/** Column builder for a `field.decimal` with no `@precision`: a `Column`, unbounded. */ - |internal fun Table.portableDecimal(name: String): Column = - | registerColumn(name, MetaUnboundedDecimalColumnType()) - | - |/** - | * GENERATED — do not hand-edit. An `isArray` decimal column: a native `NUMERIC[]` on Postgres, and on - | * MySQL and SQLite (no array type) a JSON text array of canonical strings. Elements are read exactly. - | */ - |internal class MetaDecimalArrayColumnType : ColumnType>() { - | private fun isMySql(): Boolean = currentDialect.name.let { it.equals("mysql", ignoreCase = true) || it.equals("mariadb", ignoreCase = true) } - | private fun decimalOf(element: Any): BigDecimal = if (element is BigDecimal) element else BigDecimal(element.toString()) - | private fun json(value: List): String = value.joinToString(",", "[", "]") { "\"" + MetaDecimalWire.format(it) + "\"" } - | override fun sqlType(): String = if (isPostgres()) "NUMERIC[]" else if (isMySql()) "JSON" else "TEXT" - | override fun valueFromDB(value: Any): List = when (value) { - | is java.sql.Array -> (value.array as Array<*>).map { decimalOf(it!!) } - | is Array<*> -> value.map { decimalOf(it!!) } - | is List<*> -> value.map { decimalOf(it!!) } - | else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { MetaDecimalWire.fromNode(it) } - | } - | override fun notNullValueToDB(value: List): Any = - | if (isPostgres()) value.toTypedArray() else json(value) - | override fun nonNullValueToString(value: List): String = - | if (isPostgres()) value.joinToString(",", "ARRAY[", "]::numeric[]") { it.toPlainString() } else "'" + json(value) + "'" - | override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) { - | if (value is Array<*>) { - |$decimalArrayBind - | } else { - | super.setParameter(stmt, index, value) - | } - | } - |} - | - |/** Column builder for an `isArray` `field.decimal`: a `Column>`. */ - |internal fun Table.portableDecimalArray(name: String): Column> = - | registerColumn(name, MetaDecimalArrayColumnType()) - |""".trimMargin() } /** @@ -2205,27 +2156,6 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` persisted through the real - | * Postgres `uuid` type. Every SQL/JDBC concern is DELEGATED to Exposed's own - | * `java.util.UUID`-backed `UUIDColumnType` — this class converts ONLY at the - | * Kotlin-value boundary, so the generated entity/controller see a plain `String` - | * (matching every other MetaObjects port) while the column keeps its native uuid - | * physical type. - | */ - |internal class MetaUuidStringColumnType : ColumnType() { - | private val delegate = UUIDColumnType() - | override fun sqlType(): String = delegate.sqlType() - | override fun valueFromDB(value: Any): String = - | requireNotNull(delegate.valueFromDB(value)) { "null uuid column value" }.toString() - | override fun notNullValueToDB(value: String): Any = - | delegate.notNullValueToDB(java.util.UUID.fromString(value)) - | override fun nonNullValueToString(value: String): String = - | delegate.nonNullValueToString(java.util.UUID.fromString(value)) - | override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) = - | delegate.setParameter(stmt, index, value) - |} - | - |/** Column builder for `field.string @dbColumnType=uuid`: a `Column` over a native `uuid` column. */ - |internal fun Table.uuidString(name: String): Column = - | registerColumn(name, MetaUuidStringColumnType()) - |""".trimMargin() + fun writeUuidStringSupport(w: KotlinWriter, api: ExposedApi) { + // Imports keyed by + // [ExposedApi]. The delegate's FQN is the one textual difference between versions + // (issue #390 — 1.x's bare `UUIDColumnType` binds `kotlin.uuid.Uuid`; `javaUuid`'s + // `UUIDColumnType` is the java.util.UUID-backed replacement — the SAME substitution + // [KotlinTypeMapper.exposedColumnSpec] already makes for a native `field.uuid` column + // under 1.x). + for (name in listOf("Column", "ColumnType", "Table")) w.use(ExposedImports.core(api, name)) + w.use(ExposedImports.statementsApi(api, "PreparedStatementApi")) + w.use(if (api == ExposedApi.V1) ExposedImports.javaUuid("UUIDColumnType") else ExposedImports.core(api, "UUIDColumnType")) + w.text( + """ + /** + * GENERATED — do not hand-edit. + * Custom Exposed column type for `field.string @dbColumnType=uuid` (ADR-0037 + * physical-only escape hatch): a `Column` persisted through the real + * Postgres `uuid` type. Every SQL/JDBC concern is DELEGATED to Exposed's own + * `java.util.UUID`-backed `UUIDColumnType` — this class converts ONLY at the + * Kotlin-value boundary, so the generated entity/controller see a plain `String` + * (matching every other MetaObjects port) while the column keeps its native uuid + * physical type. + */ + internal class MetaUuidStringColumnType : ColumnType() { + private val delegate = UUIDColumnType() + override fun sqlType(): String = delegate.sqlType() + override fun valueFromDB(value: Any): String = + requireNotNull(delegate.valueFromDB(value)) { "null uuid column value" }.toString() + override fun notNullValueToDB(value: String): Any = + delegate.notNullValueToDB(java.util.UUID.fromString(value)) + override fun nonNullValueToString(value: String): String = + delegate.nonNullValueToString(java.util.UUID.fromString(value)) + override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) = + delegate.setParameter(stmt, index, value) + } + + /** Column builder for `field.string @dbColumnType=uuid`: a `Column` over a native `uuid` column. */ + internal fun Table.uuidString(name: String): Column = + registerColumn(name, MetaUuidStringColumnType()) + """ + ) + } /** * File name (sans `.kt`) of the per-package support file holding the shared Jackson @@ -2300,25 +2243,29 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase?): ").append(mirror).append("? {\n") - append(" if (d == null) return null\n") - append(" return ").append(mirror).append("(\n") - for (field in fields) { - append(" ").append(field.name).append(" = ").append(fromMapArg(field)).append(",\n") - } - append(" )\n") - append(" }\n") - // The two helpers only a nested value object needs: `asMap` for a single nested - // object (and inside mapObjectList), `mapObjectList` for an array of them. - val nestedFields = fields.filter { objectRefValueObject(it) != null } - if (nestedFields.isNotEmpty()) { - append("\n") - append(" /** Null-tolerant cast of an assembled value to a Map (a ValueObject IS a Map). */\n") - append(" @Suppress(\"UNCHECKED_CAST\")\n") - append(" private fun asMap(v: Any?): Map? = v as? Map\n") + val w = KotlinWriter().packageName(pkg) + w.header("// GENERATED — DO NOT EDIT — lenient extraction mirror of value object `${vo.name}`") + w.use("com.metaobjects.render.extract.ExtractMap") + w.doc( + "All-nullable mirror of [$short] for tolerant extraction: a partial model", + "reply still maps. [toStrict] converts it once no `@required` field was lost or malformed.", + ) + val properties = fields.map { "val ${it.name}: ${mirrorPropertyType(it)} = null" } + w.block(listOf("data class $mirror", CodeWriter.list("(", properties, ")"), " {")) { + w.doc("The strict [$short]. Call only once the extract report shows no lost or malformed required field.") + w.block("fun toStrict(): $short = $short(", ")") { + for (field in fields) { + w.line("${field.name} = ${strictArg(field, vo, provided)},") + } } - if (nestedFields.any { it.isArrayType() }) { - append("\n") - append(" /** Map each element of an assembled List via [fn]; null/absent -> null; non-Map elements skipped. */\n") - append(" private fun mapObjectList(d: Map, key: String, fn: (Map) -> T): List? {\n") - append(" val v = d[key] as? List<*> ?: return null\n") - append(" val outList = ArrayList(v.size)\n") - append(" for (elem in v) {\n") - append(" val m = asMap(elem)\n") - append(" if (m != null) outList.add(fn(m))\n") - append(" }\n") - append(" return outList\n") - append(" }\n") + w.blank() + w.block("companion object {") { + w.doc("Map an assembled ValueObject (a Map) onto the typed mirror; null-tolerant.") + w.line("@JvmStatic") + w.block("fun fromMap(d: Map?): $mirror? {") { + w.line("if (d == null) return null") + w.block("return $mirror(", ")") { + for (field in fields) { + w.line("${field.name} = ${fromMapArg(field)},") + } + } + } + // The two helpers only a nested value object needs: `asMap` for a single nested + // object (and inside mapObjectList), `mapObjectList` for an array of them. + val nestedFields = fields.filter { objectRefValueObject(it) != null } + if (nestedFields.isNotEmpty()) { + w.blank() + w.doc("Null-tolerant cast of an assembled value to a Map (a ValueObject IS a Map).") + w.line("@Suppress(\"UNCHECKED_CAST\")") + w.line("private fun asMap(v: Any?): Map? = v as? Map") + } + if (nestedFields.any { it.isArrayType() }) { + w.blank() + w.doc("Map each element of an assembled List via [fn]; null/absent -> null; non-Map elements skipped.") + w.block("private fun mapObjectList(d: Map, key: String, fn: (Map) -> T): List? {") { + w.line("val v = d[key] as? List<*> ?: return null") + w.line("val outList = ArrayList(v.size)") + w.block("for (elem in v) {") { + w.line("val m = asMap(elem)") + w.line("if (m != null) outList.add(fn(m))") + } + w.line("return outList") + } + } } - append(" }\n") - append("}\n") } + return w.toString() } /** @@ -256,7 +246,7 @@ object KotlinExtractSchemaEmitter { // Scalar arrays: the mirror is always List (ExtractMap.asStringList stringifies // every element), so each element parses to the strict element type. if (field.isArrayType()) { - val conv = fromStringConversion(field, KotlinTypeMapper.payloadTypeName(field)) + val conv = fromStringConversion(field, KotlinTypeMapper.payloadTypeName(field).toString()) val base = if (nullable) "$name?.filterNotNull()" else "$name!!.filterNotNull()" if (conv == null) return base return if (nullable) "$base?.map { $conv }" else "$base.map { $conv }" @@ -275,7 +265,8 @@ object KotlinExtractSchemaEmitter { } // A single scalar: parse when the mirror leaf is a String and the strict type is not. - val strict = KotlinTypeMapper.payloadTypeName(field) + // The type mapper describes a type as a KotlinPoet value; it is compared by its qualified name. + val strict = KotlinTypeMapper.payloadTypeName(field).toString() val conv = if (mirrorScalar(field) == strict) null else fromStringConversion(field, strict) return when { conv == null && nullable -> name @@ -285,13 +276,13 @@ object KotlinExtractSchemaEmitter { } } - /** The mirror's non-null leaf type for a single scalar (see [mirrorPropertyType]). */ - private fun mirrorScalar(field: MetaField<*>): TypeName = when (field) { - is IntegerField -> INT - is LongField -> LONG - is DoubleField -> DOUBLE - is BooleanField -> BOOLEAN - else -> STRING + /** The qualified name of the mirror's non-null leaf type for a single scalar (see [mirrorPropertyType]). */ + private fun mirrorScalar(field: MetaField<*>): String = when (field) { + is IntegerField -> "kotlin.Int" + is LongField -> "kotlin.Long" + is DoubleField -> "kotlin.Double" + is BooleanField -> "kotlin.Boolean" + else -> "kotlin.String" } /** @@ -299,16 +290,16 @@ object KotlinExtractSchemaEmitter { * [strict] is itself `String`. Fails loud at codegen time for a type with no safe parse, rather * than emitting Kotlin that does not compile. */ - private fun fromStringConversion(field: MetaField<*>, strict: TypeName): String? { + private fun fromStringConversion(field: MetaField<*>, strict: String): String? { if (KotlinTypeMapper.isJsonbOpenBag(field)) return "kotlinx.serialization.json.Json.parseToJsonElement(it)" return when (strict) { - STRING -> null - INT -> "it.toInt()" - LONG -> "it.toLong()" // also field.currency (minor-unit Long) - DOUBLE -> "it.toDouble()" - FLOAT -> "it.toFloat()" - BOOLEAN -> "it.toBoolean()" - else -> when (strict.toString()) { + "kotlin.String" -> null + "kotlin.Int" -> "it.toInt()" + "kotlin.Long" -> "it.toLong()" // also field.currency (minor-unit Long) + "kotlin.Double" -> "it.toDouble()" + "kotlin.Float" -> "it.toFloat()" + "kotlin.Boolean" -> "it.toBoolean()" + else -> when (strict) { "java.util.UUID" -> "java.util.UUID.fromString(it)" "java.math.BigDecimal" -> "java.math.BigDecimal(it)" "java.net.URI" -> "java.net.URI(it)" diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRelationsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRelationsGenerator.kt index 8c1833ef5d..5203bb548c 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRelationsGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRelationsGenerator.kt @@ -14,6 +14,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.generator.GeneratorIOWriter import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase @@ -23,12 +24,8 @@ import com.metaobjects.loader.MetaDataLoader import com.metaobjects.`object`.MetaObject import com.metaobjects.relationship.CompositionRelationship import com.metaobjects.relationship.MetaRelationship -import com.squareup.kotlinpoet.ClassName -import com.squareup.kotlinpoet.LONG -import com.squareup.kotlinpoet.TypeName import java.io.OutputStream import java.io.PrintWriter -import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import com.metaobjects.generator.util.GeneratedFileWriter @@ -165,84 +162,79 @@ open class KotlinRelationsGenerator : MultiFileDirectGeneratorBase() } if (helpers.isEmpty() && m2mNavs.isEmpty() && reverseFks.isEmpty()) return - val source = buildString { - if (pkg.isNotEmpty()) { - append("package $pkg\n\n") - } - append("import ${ExposedImports.jdbc(api, "Query")}\n") - if (api == ExposedApi.V1) { - // issue #390: `eq` is a SqlExpressionBuilder-scoped member under 0.x, brought - // into scope implicitly by `.where{}`'s `SqlExpressionBuilder.() -> Op` - // receiver — so 0.x only imports it explicitly when a call site (the m2mNavs - // join/where blocks below) needs it OUTSIDE a `.where{}`. `Query.where()` takes a - // receiver-LESS lambda under 1.x (`() -> Op`), so every call site below — - // the plain composition helpers' `.where{}`, the reverse-FK finders', AND the - // m2mNavs joins — needs the plain top-level import; unconditional here because - // this function only reaches this point when at least one of helpers/m2mNavs/ - // reverseFks is non-empty (the early return above), and all three use `eq`. - append("import ${ExposedImports.core(api, "eq")}\n") - // `inList` (the batched reverse-FK finder) is the same 0.x-implicit/1.x-explicit - // story as `eq` — conditional because it is the ONLY site that uses it. - if (reverseFks.isNotEmpty()) append("import ${ExposedImports.core(api, "inList")}\n") - } - if (m2mNavs.isNotEmpty()) { - append("import ${ExposedImports.core(api, "JoinType")}\n") - if (api == ExposedApi.V0) { - // 0.x — UNCHANGED (byte-identical). See the V1 branch above for why this - // import is conditional on m2mNavs under 0.x but unconditional under 1.x. - append("import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq\n") - } - // `and` backs both the symmetric branch's directional ON clause (no neq - // exclusion — keeps the self endpoint) AND a non-symmetric nav whose TARGET is a - // TPH subtype (FW-3): the shared storage table's rows are ANDed with the - // discriminator so a sibling subtype's row can't come back. `or` is symmetric-only. - if (m2mNavs.any { it.nav.symmetric }) { - append("import ${ExposedImports.core(api, "or")}\n") - } - if (m2mNavs.any { it.nav.symmetric || it.nav.targetDiscriminator != null }) { - append("import ${ExposedImports.core(api, "and")}\n") - } - } - append("import ${ExposedImports.jdbc(api, "selectAll")}\n") - // java.util.UUID appears in helper signatures when the owner's PK (or a - // reverse-FK value type) is uuid — the param types were already derived, but - // without this import the generated file had an unresolved reference. Emitted - // conditionally so uuid-free files stay byte-identical. - val typeImports = (listOf(pkRendered.import) + reverseFks.map { it.valueImport }) - .filterNotNull().toSortedSet() - for (line in typeImports) append("import $line\n") - val crossPackageTables = KotlinM2mSupport.importLines(m2mNavs.map { it.nav }, pkg, junction = true, dataClass = false) + - helpers.filter { it.targetPackage != pkg } - .map { if (it.targetPackage.isEmpty()) it.targetTable else "${it.targetPackage}.${it.targetTable}" } - for (line in crossPackageTables.toSortedSet()) append("import $line\n") - append("\n") - append("/** GENERATED — extension fns for `$ownerShort` to-many relationships. Do not hand-edit. */\n") - var first = true - for (h in helpers) { - if (!first) append("\n") - first = false - append("/** Query `$ownerShort.${h.relShortName}` (cardinality=many) on the ${h.targetTable.removeSuffix("Table")} side. */\n") - append("fun $ownerTable.${h.relShortName}Query($fkColName: $pkParamSimpleName): Query =\n") - append(" ${h.targetTable}.selectAll().where { ${h.targetTable}.$fkColName eq $fkColName }\n") + val w = KotlinWriter().packageName(pkg) + w.use(ExposedImports.jdbc(api, "Query")) + if (api == ExposedApi.V1) { + // issue #390: `eq` is a SqlExpressionBuilder-scoped member under 0.x, brought + // into scope implicitly by `.where{}`'s `SqlExpressionBuilder.() -> Op` + // receiver — so 0.x only imports it explicitly when a call site (the m2mNavs + // join/where blocks below) needs it OUTSIDE a `.where{}`. `Query.where()` takes a + // receiver-LESS lambda under 1.x (`() -> Op`), so every call site below — + // the plain composition helpers' `.where{}`, the reverse-FK finders', AND the + // m2mNavs joins — needs the plain top-level import; unconditional here because + // this function only reaches this point when at least one of helpers/m2mNavs/ + // reverseFks is non-empty (the early return above), and all three use `eq`. + w.use(ExposedImports.core(api, "eq")) + // `inList` (the batched reverse-FK finder) is the same 0.x-implicit/1.x-explicit + // story as `eq` — conditional because it is the ONLY site that uses it. + if (reverseFks.isNotEmpty()) w.use(ExposedImports.core(api, "inList")) + } + if (m2mNavs.isNotEmpty()) { + w.use(ExposedImports.core(api, "JoinType")) + // 0.x: see the V1 branch above for why this import is conditional on m2mNavs under + // 0.x but unconditional under 1.x. + if (api == ExposedApi.V0) w.use("org.jetbrains.exposed.sql.SqlExpressionBuilder.eq") + // `and` backs both the symmetric branch's directional ON clause (no neq + // exclusion — keeps the self endpoint) AND a non-symmetric nav whose TARGET is a + // TPH subtype (FW-3): the shared storage table's rows are ANDed with the + // discriminator so a sibling subtype's row can't come back. `or` is symmetric-only. + if (m2mNavs.any { it.nav.symmetric }) w.use(ExposedImports.core(api, "or")) + if (m2mNavs.any { it.nav.symmetric || it.nav.targetDiscriminator != null }) { + w.use(ExposedImports.core(api, "and")) } + } + w.use(ExposedImports.jdbc(api, "selectAll")) + // java.util.UUID appears in helper signatures when the owner's PK (or a + // reverse-FK value type) is uuid — the param types were already derived, but + // without this import the generated file had an unresolved reference. + for (imp in listOf(pkRendered.import) + reverseFks.map { it.valueImport }) { + if (imp != null) w.use(imp) + } + val crossPackageTables = KotlinM2mSupport.importLines(m2mNavs.map { it.nav }, pkg, junction = true, dataClass = false) + + helpers.filter { it.targetPackage != pkg } + .map { if (it.targetPackage.isEmpty()) it.targetTable else "${it.targetPackage}.${it.targetTable}" } + for (imp in crossPackageTables) w.use(imp) + + w.doc("GENERATED — extension fns for `$ownerShort` to-many relationships. Do not hand-edit.") + var first = true + for (h in helpers) { + if (!first) w.blank() + first = false + w.doc("Query `$ownerShort.${h.relShortName}` (cardinality=many) on the ${h.targetTable.removeSuffix("Table")} side.") + w.line("fun $ownerTable.${h.relShortName}Query($fkColName: $pkParamSimpleName): Query =") + w.indented { w.line("${h.targetTable}.selectAll().where { ${h.targetTable}.$fkColName eq $fkColName }") } + } - // FR-018 M:N junction-join query helpers. Each emits an Exposed Query that - // INNER-JOINs the target table to the junction on the derived target-side FK, - // returning the target rows whose junction row matches the source id. The - // junction FK columns are derived (KotlinM2mSupport → M2MFields), never restated. - // * hetero / directed self-join: WHERE junction. = :id - // * symmetric self-join: WHERE junction. = :id - // OR junction. = :id (union-on-read) - // The join keys the target by its PRIMARY KEY against the junction's target-side - // FK; the source filter uses the junction's source-side FK. Related-row order is - // not contractual. - for (named in m2mNavs) { - val nav = named.nav - if (!first) append("\n") - first = false - val symMarker = if (nav.symmetric) " (symmetric — union on read)" else "" - append("/** Query `$ownerShort.${nav.relationName}` (M:N via ${nav.junctionShortName})$symMarker — the related ${nav.targetShortName} rows. */\n") - append("fun $ownerTable.${named.queryFnName}(sourceId: $pkParamSimpleName): Query =\n") + // FR-018 M:N junction-join query helpers. Each emits an Exposed Query that + // INNER-JOINs the target table to the junction on the derived target-side FK, + // returning the target rows whose junction row matches the source id. The + // junction FK columns are derived (KotlinM2mSupport → M2MFields), never restated. + // * hetero / directed self-join: WHERE junction. = :id + // * symmetric self-join: WHERE junction. = :id + // OR junction. = :id (union-on-read) + // The join keys the target by its PRIMARY KEY against the junction's target-side + // FK; the source filter uses the junction's source-side FK. Related-row order is + // not contractual. + for (named in m2mNavs) { + val nav = named.nav + if (!first) w.blank() + first = false + val symMarker = if (nav.symmetric) " (symmetric — union on read)" else "" + val junction = nav.junctionTableObj + val target = nav.targetTableObj + w.doc("Query `$ownerShort.${nav.relationName}` (M:N via ${nav.junctionShortName})$symMarker — the related ${nav.targetShortName} rows.") + w.line("fun $ownerTable.${named.queryFnName}(sourceId: $pkParamSimpleName): Query =") + w.indented { if (nav.symmetric) { // Symmetric storage is single-row; a friend appears via EITHER FK column. // Union-on-read: for each junction row touching the source, the related id is @@ -256,15 +248,13 @@ open class KotlinRelationsGenerator : MultiFileDirectGeneratorBase() // (Alice is her own friend). No `neq sourceId` exclusion (that would drop (a,a)), // and the directional ON clause already constrains to junction rows touching the // source, so no extra WHERE is needed. - append(" ${nav.targetTableObj}.join(${nav.junctionTableObj}, JoinType.INNER) {\n") - append(" ((${nav.junctionTableObj}.${nav.sourceField} eq ${nav.targetTableObj}.${nav.targetPkField}) and (${nav.junctionTableObj}.${nav.targetField} eq sourceId)) or\n") - append(" ((${nav.junctionTableObj}.${nav.targetField} eq ${nav.targetTableObj}.${nav.targetPkField}) and (${nav.junctionTableObj}.${nav.sourceField} eq sourceId))\n") - append(" }.selectAll()") val symDisc = nav.targetDiscriminator - if (symDisc != null) { - append(".where { ${nav.targetTableObj}.${symDisc.column} eq ${symDisc.valueExpr} }\n") - } else { - append("\n") + val tail = if (symDisc != null) ".where { $target.${symDisc.column} eq ${symDisc.valueExpr} }" else "" + w.block("$target.join($junction, JoinType.INNER) {", "}.selectAll()$tail") { + w.line("(($junction.${nav.sourceField} eq $target.${nav.targetPkField}) and ($junction.${nav.targetField} eq sourceId)) or") + w.indented { + w.line("(($junction.${nav.targetField} eq $target.${nav.targetPkField}) and ($junction.${nav.sourceField} eq sourceId))") + } } } else { // Hetero / directed self-join: join the target by its PK to the junction's @@ -272,47 +262,48 @@ open class KotlinRelationsGenerator : MultiFileDirectGeneratorBase() // TPH-subtype target ANDs the discriminator into the SAME where — the shared // storage table's join keeps every subtype's rows, so this is what narrows the // result back to just the declared target's own rows. - append(" ${nav.targetTableObj}.join(${nav.junctionTableObj}, JoinType.INNER) { ${nav.targetTableObj}.${nav.targetPkField} eq ${nav.junctionTableObj}.${nav.targetField} }\n") - append(" .selectAll()\n") - val disc = nav.targetDiscriminator - if (disc != null) { - append(" .where { (${nav.junctionTableObj}.${nav.sourceField} eq sourceId) and (${nav.targetTableObj}.${disc.column} eq ${disc.valueExpr}) }\n") - } else { - append(" .where { ${nav.junctionTableObj}.${nav.sourceField} eq sourceId }\n") + w.line("$target.join($junction, JoinType.INNER) { $target.${nav.targetPkField} eq $junction.${nav.targetField} }") + w.indented { + w.line(".selectAll()") + val disc = nav.targetDiscriminator + if (disc != null) { + w.line(".where { ($junction.${nav.sourceField} eq sourceId) and ($target.${disc.column} eq ${disc.valueExpr}) }") + } else { + w.line(".where { $junction.${nav.sourceField} eq sourceId }") + } } } } + } - // ADR-0038 reverse navigation — one finder PAIR per FK this entity holds - // (each single-field identity.reference). The referenced entity T navigates to - // its referencing E rows by calling these with a T id. The fn name derives from - // the FK FIELD (PascalCased, trailing `Id` dropped), unique within E by - // construction — so same-pair FKs (GameSession → Scene ×3) yield DISTINCT finders - // (findByCurrentScene / findByLastOpeningNarrativeScene / - // findByTransitioningFromScene), never colliding, with no @reverseName vocabulary. - // NOT a lazy Exposed `referrersOn` reverse collection (N+1 + needs an open - // transaction): each is a plain single indexed query (WHERE fk = ?), with a - // batched variant (WHERE fk IN (…)) for anti-N+1 loading of many parents. The - // returned Query stays compositional (chain .orderBy/.limit before materialising). - for (fk in reverseFks) { - if (!first) append("\n") - first = false - val col = KotlinNaming.safeColumnProperty(fk.fkField, exposedApi()) - val single = KotlinNaming.reverseFinderName(fk.fkField) - val batched = KotlinNaming.reverseFinderInName(fk.fkField) - append("/** Reverse nav: the $ownerShort rows whose `${fk.fkField}` FK points at the given ${fk.targetShortName} id (single indexed query). */\n") - append("fun $ownerTable.$single(${fk.fkField}: ${fk.valueType}): Query =\n") - append(" $ownerTable.selectAll().where { $ownerTable.$col eq ${fk.fkField} }\n") - append("\n") - append("/** Reverse nav (batched, anti-N+1): the $ownerShort rows whose `${fk.fkField}` FK is IN the given ${fk.targetShortName} ids. */\n") - append("fun $ownerTable.$batched(${fk.fkField}s: List<${fk.valueType}>): Query =\n") - append(" $ownerTable.selectAll().where { $ownerTable.$col inList ${fk.fkField}s }\n") - } + // ADR-0038 reverse navigation — one finder PAIR per FK this entity holds + // (each single-field identity.reference). The referenced entity T navigates to + // its referencing E rows by calling these with a T id. The fn name derives from + // the FK FIELD (PascalCased, trailing `Id` dropped), unique within E by + // construction — so same-pair FKs (GameSession → Scene ×3) yield DISTINCT finders + // (findByCurrentScene / findByLastOpeningNarrativeScene / + // findByTransitioningFromScene), never colliding, with no @reverseName vocabulary. + // NOT a lazy Exposed `referrersOn` reverse collection (N+1 + needs an open + // transaction): each is a plain single indexed query (WHERE fk = ?), with a + // batched variant (WHERE fk IN (…)) for anti-N+1 loading of many parents. The + // returned Query stays compositional (chain .orderBy/.limit before materialising). + for (fk in reverseFks) { + if (!first) w.blank() + first = false + val col = KotlinNaming.safeColumnProperty(fk.fkField, exposedApi()) + val single = KotlinNaming.reverseFinderName(fk.fkField) + val batched = KotlinNaming.reverseFinderInName(fk.fkField) + w.doc("Reverse nav: the $ownerShort rows whose `${fk.fkField}` FK points at the given ${fk.targetShortName} id (single indexed query).") + w.line("fun $ownerTable.$single(${fk.fkField}: ${fk.valueType}): Query =") + w.indented { w.line("$ownerTable.selectAll().where { $ownerTable.$col eq ${fk.fkField} }") } + w.blank() + w.doc("Reverse nav (batched, anti-N+1): the $ownerShort rows whose `${fk.fkField}` FK is IN the given ${fk.targetShortName} ids.") + w.line("fun $ownerTable.$batched(${fk.fkField}s: List<${fk.valueType}>): Query =") + w.indented { w.line("$ownerTable.selectAll().where { $ownerTable.$col inList ${fk.fkField}s }") } } val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(ownerShort + "Relations.kt") - outFile.parent?.let { Files.createDirectories(it) } - GeneratedFileWriter.write(outFile, source) + GeneratedFileWriter.write(outFile, w.toString()) } /** @@ -359,9 +350,11 @@ open class KotlinRelationsGenerator : MultiFileDirectGeneratorBase() * Render [type] for text emission. A [ClassName] prints its simple name and imports its * canonical name (nothing for the auto-imported `kotlin` / `java.lang` packages). Any other * shape (parameterized, nullable, ...) prints fully qualified, which is always valid. + * [KotlinTypeMapper] still describes a type as a KotlinPoet value, so it is read here by its + * qualified name; nothing in this file is laid out by KotlinPoet. */ - protected fun renderType(type: TypeName): RenderedType { - if (type !is ClassName || type.isNullable) return RenderedType(type.toString(), null) + protected fun renderType(type: com.squareup.kotlinpoet.TypeName): RenderedType { + if (type !is com.squareup.kotlinpoet.ClassName || type.isNullable) return RenderedType(type.toString(), null) val autoImported = type.packageName == "kotlin" || type.packageName == "java.lang" return RenderedType(type.simpleNames.joinToString("."), if (autoImported) null else type.topLevelClassName().canonicalName) } @@ -384,7 +377,7 @@ open class KotlinRelationsGenerator : MultiFileDirectGeneratorBase() val targetShort = child.targetEntity?.let { PackageMapping.splitFqn(it).second } ?: "" val rendered = entity.metaFields.firstOrNull { it.name == fkField }?.let { f -> runCatching { renderType(KotlinTypeMapper.kotlinTypeName(f)) }.getOrNull() - } ?: renderType(LONG) + } ?: renderType(com.squareup.kotlinpoet.LONG) out.add(ReverseFk(fkField, targetShort, rendered.name, rendered.import)) } return out @@ -400,15 +393,15 @@ open class KotlinRelationsGenerator : MultiFileDirectGeneratorBase() * the table generator: defensive defaults rather than throwing on * partially-formed metadata. */ - protected open fun primaryKeyKotlinType(entity: MetaObject): TypeName { + protected open fun primaryKeyKotlinType(entity: MetaObject): com.squareup.kotlinpoet.TypeName { // ADR-0039: identities are inheritable — RESOLVE via getIdentities(true); // entity.children (own-only) would miss an inherited primary identity. val primary = entity.getIdentities(true) .filterIsInstance() - .firstOrNull { it.isPrimary } ?: return LONG - val pkFieldName = KotlinGenUtil.keyFields(entity, primary).firstOrNull() ?: return LONG - val pkField = entity.metaFields.firstOrNull { it.name == pkFieldName } ?: return LONG - return runCatching { KotlinTypeMapper.kotlinTypeName(pkField) }.getOrDefault(LONG) + .firstOrNull { it.isPrimary } ?: return com.squareup.kotlinpoet.LONG + val pkFieldName = KotlinGenUtil.keyFields(entity, primary).firstOrNull() ?: return com.squareup.kotlinpoet.LONG + val pkField = entity.metaFields.firstOrNull { it.name == pkFieldName } ?: return com.squareup.kotlinpoet.LONG + return runCatching { KotlinTypeMapper.kotlinTypeName(pkField) }.getOrDefault(com.squareup.kotlinpoet.LONG) } // === MultiFileDirectGeneratorBase abstract-method stubs ==================== diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRepositoryGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRepositoryGenerator.kt index bc0ab3489e..3ec4df175e 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRepositoryGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRepositoryGenerator.kt @@ -12,6 +12,8 @@ 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.generator.writer.CodeWriter import com.metaobjects.field.MapField import com.metaobjects.field.ObjectField @@ -23,7 +25,6 @@ import com.metaobjects.`object`.MetaObject import com.metaobjects.source.MetaSource import java.io.OutputStream import java.io.PrintWriter -import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import org.slf4j.LoggerFactory @@ -172,24 +173,26 @@ open class KotlinRepositoryGenerator : MultiFileDirectGeneratorBase( val hasAutoSet = autoSetFields.isNotEmpty() val hasOnUpdate = onUpdateFields.isNotEmpty() - // Emit the non-PK, non-autoSet ("regular") columns of an insert into the current builder, + val w = KotlinWriter().packageName(pkg) + + // Emit the non-PK, non-autoSet ("regular") columns of an insert into the current block, // then (when present) the shared autoSet stamping. `preserve` == insertPreserving: write // the autoSet columns verbatim from the dto rather than stamping now(). - fun StringBuilder.appendInsertColumns(preserve: Boolean) { + fun insertColumns(preserve: Boolean) { for (field in scalarFields) { if (field.name == pkFieldName) continue if (field.name in autoSetNames) continue - append(" it[$writeObj.${field.name}] = dto.${field.name}\n") + w.line("it[$writeObj.${field.name}] = dto.${field.name}") } if (hasAutoSet) { - append(" applyAutoSetColumns(it${if (preserve) ", dto, stampAutoSet = false" else ""})\n") + w.line("applyAutoSetColumns(it", if (preserve) ", dto, stampAutoSet = false" else "", ")") } } // The whole insert transaction body, branching on `identity.primary @generation`. Shared by // `insert` (preserve=false → stamp) and `insertPreserving` (preserve=true → verbatim) so the // PK/read-back logic has one definition. - fun StringBuilder.appendInsertBody(preserve: Boolean) { + fun insertBody(preserve: Boolean) { // Writes target the write table; the by-PK read-back routes to the read object // (the view for a write-through entity) so the returned entity carries derived fields. // #214 cross-port notes: (D4) the re-read keys on the SINGLE primary key @@ -202,197 +205,197 @@ open class KotlinRepositoryGenerator : MultiFileDirectGeneratorBase( // data-oriented ports degrade to the table row instead) — a documented limitation. when { incrementPk -> { - append(" val newId = $writeObj.insert {\n") - appendInsertColumns(preserve) - append(" }[$writeObj.$pkFieldName]\n") - append(" $readObj.selectAll().where { $readObj.$pkFieldName eq newId }.single().let(::rowTo$shortName)\n") + w.block("val newId = $writeObj.insert {", "}[$writeObj.$pkFieldName]") { insertColumns(preserve) } + w.line("$readObj.selectAll().where { $readObj.$pkFieldName eq newId }.single().let(::rowTo$shortName)") } uuidPk -> { - append(" val newId = UUID.randomUUID()\n") - append(" $writeObj.insert {\n") - append(" it[$writeObj.$pkFieldName] = newId\n") - appendInsertColumns(preserve) - append(" }\n") - append(" $readObj.selectAll().where { $readObj.$pkFieldName eq newId }.single().let(::rowTo$shortName)\n") + w.line("val newId = UUID.randomUUID()") + w.block("$writeObj.insert {") { + w.line("it[$writeObj.$pkFieldName] = newId") + insertColumns(preserve) + } + w.line("$readObj.selectAll().where { $readObj.$pkFieldName eq newId }.single().let(::rowTo$shortName)") } else -> { - append(" $writeObj.insert {\n") - append(" it[$writeObj.$pkFieldName] = dto.$pkFieldName\n") - appendInsertColumns(preserve) - append(" }\n") - append(" $readObj.selectAll().where { $readObj.$pkFieldName eq dto.$pkFieldName }.single().let(::rowTo$shortName)\n") + w.block("$writeObj.insert {") { + w.line("it[$writeObj.$pkFieldName] = dto.$pkFieldName") + insertColumns(preserve) + } + w.line("$readObj.selectAll().where { $readObj.$pkFieldName eq dto.$pkFieldName }.single().let(::rowTo$shortName)") } } } - val src = buildString { - if (pkg.isNotEmpty()) append("package $pkg\n\n") - - append("import ${ExposedImports.core(api, "ResultRow")}\n") - // issue #390: under 1.x, SqlExpressionBuilder is gone from the operators' - // perspective — eq/and/... are top-level imports and deleteWhere's lambda no - // longer provides SqlExpressionBuilder as an implicit receiver (see [delete]). - if (api == ExposedApi.V1) append("import ${ExposedImports.core(api, "eq")}\n") - else append("import ${ExposedImports.core(api, "SqlExpressionBuilder")}\n") - append("import ${ExposedImports.jdbc(api, "deleteWhere")}\n") - append("import ${ExposedImports.jdbc(api, "insert")}\n") - append("import ${ExposedImports.jdbc(api, "selectAll")}\n") - // The @autoSet stamping helper writes through the common insert/update supertype. - if (hasAutoSet) append("import ${ExposedImports.statements(api, "UpdateBuilder")}\n") - append("import ${ExposedImports.statements(api, "UpdateStatement")}\n") - append("import ${ExposedImports.jdbc(api, "update")}\n") - append("import ${ExposedImports.transactions(api, "transaction")}\n") - // java.util.UUID surfaces when the PK is a client-generated uuid, or any column is uuid. - if (uuidPk || hasUuidColumn) append("import java.util.UUID\n") - append("\n") - - append("/**\n") - append(" * GENERATED — persistence repository base for $shortName. Do not hand-edit.\n") - append(" *\n") - append(" * `open` so a consumer can subclass and override; NOT `@Repository` (a subclass\n") - append(" * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2).\n") - append(" */\n") - append("open class $repoName {\n\n") - + w.use(ExposedImports.core(api, "ResultRow")) + // issue #390: under 1.x, SqlExpressionBuilder is gone from the operators' + // perspective — eq/and/... are top-level imports and deleteWhere's lambda no + // longer provides SqlExpressionBuilder as an implicit receiver (see [delete]). + if (api == ExposedApi.V1) w.use(ExposedImports.core(api, "eq")) + else w.use(ExposedImports.core(api, "SqlExpressionBuilder")) + w.use(ExposedImports.jdbc(api, "deleteWhere")) + w.use(ExposedImports.jdbc(api, "insert")) + w.use(ExposedImports.jdbc(api, "selectAll")) + // The @autoSet stamping helper writes through the common insert/update supertype. + if (hasAutoSet) w.use(ExposedImports.statements(api, "UpdateBuilder")) + w.use(ExposedImports.statements(api, "UpdateStatement")) + w.use(ExposedImports.jdbc(api, "update")) + w.use(ExposedImports.transactions(api, "transaction")) + // java.util.UUID surfaces when the PK is a client-generated uuid, or any column is uuid. + if (uuidPk || hasUuidColumn) w.use("java.util.UUID") + + w.doc( + "GENERATED — persistence repository base for $shortName. Do not hand-edit.", + "", + "`open` so a consumer can subclass and override; NOT `@Repository` (a subclass", + "would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2).", + ) + w.block("open class $repoName {") { // --- row-mapper (verbatim shape from the controller's rowTo) --- // Reads the READ object's row (the view for a write-through entity) and maps ALL scalar // fields incl. derived — the derived columns live only on the view. - append(" /** Map an Exposed ResultRow to the $shortName data class. */\n") - append(" open fun rowTo$shortName(row: ResultRow): $shortName = $shortName(\n") - for (field in readScalarFields) { - append(" ${field.name} = row[$readObj.${field.name}],\n") + w.doc("Map an Exposed ResultRow to the $shortName data class.") + w.block("open fun rowTo$shortName(row: ResultRow): $shortName = $shortName(", ")") { + for (field in readScalarFields) { + w.line("${field.name} = row[$readObj.${field.name}],") + } } - append(" )\n\n") + w.blank() // --- findById --- - append(" /** The $shortName with this primary key, or null. */\n") - append(" open fun findById(id: $pkParamType): $shortName? = transaction {\n") - append(" $readObj.selectAll().where { $readObj.$pkFieldName eq id }.singleOrNull()?.let(::rowTo$shortName)\n") - append(" }\n\n") + w.doc("The $shortName with this primary key, or null.") + w.block("open fun findById(id: $pkParamType): $shortName? = transaction {") { + w.line("$readObj.selectAll().where { $readObj.$pkFieldName eq id }.singleOrNull()?.let(::rowTo$shortName)") + } + w.blank() // --- @autoSet stamping (issue #203) --- if (hasAutoSet) { - append(" /**\n") - append(" * Write the `@autoSet` timestamp columns of $shortName into an insert/update builder\n") - append(" * (the CRUD layer owns them — the caller does not supply them). ONE column-list\n") - append(" * definition shared by insert / insertPreserving / update / patch:\n") - append(" * - `stampAutoSet` — stamp `now()` (base CRUD) vs. write the [dto] value verbatim\n") - append(" * (insertPreserving, for import/restore/replication that keep original timestamps);\n") - append(" * - `includeOnCreate` — write the write-once onCreate columns (insert) or skip them\n") - append(" * (update/patch never rewrite created_at — the latent lost-update bug otherwise).\n") - append(" * [dto] is only read on the verbatim path, so the stamping callers pass null.\n") - append(" * `now()` is keyed off each COLUMN's temporal type, so it generalizes beyond Instant.\n") - append(" */\n") - append(" protected open fun applyAutoSetColumns(\n") - append(" stmt: UpdateBuilder<*>,\n") - append(" dto: $shortName? = null,\n") - append(" stampAutoSet: Boolean = true,\n") - append(" includeOnCreate: Boolean = true,\n") - append(" ) {\n") - if (onCreateFields.isNotEmpty()) { - append(" if (includeOnCreate) {\n") - for (field in onCreateFields) { - append(" stmt[$writeObj.${field.name}] = if (stampAutoSet) ${nowExpr(field)} else dto!!.${field.name}\n") + w.text( + """ + /** + * Write the `@autoSet` timestamp columns of $shortName into an insert/update builder + * (the CRUD layer owns them — the caller does not supply them). ONE column-list + * definition shared by insert / insertPreserving / update / patch: + * - `stampAutoSet` — stamp `now()` (base CRUD) vs. write the [dto] value verbatim + * (insertPreserving, for import/restore/replication that keep original timestamps); + * - `includeOnCreate` — write the write-once onCreate columns (insert) or skip them + * (update/patch never rewrite created_at — the latent lost-update bug otherwise). + * [dto] is only read on the verbatim path, so the stamping callers pass null. + * `now()` is keyed off each COLUMN's temporal type, so it generalizes beyond Instant. + */ + """ + ) + val params = CodeWriter.list( + "(", + listOf( + "stmt: UpdateBuilder<*>", "dto: $shortName? = null", + "stampAutoSet: Boolean = true", "includeOnCreate: Boolean = true", + ), + ")", + ) + w.block(listOf("protected open fun applyAutoSetColumns", params, " {")) { + if (onCreateFields.isNotEmpty()) { + w.block("if (includeOnCreate) {") { + for (field in onCreateFields) { + w.line("stmt[$writeObj.${field.name}] = if (stampAutoSet) ${nowExpr(field)} else dto!!.${field.name}") + } + } + } + for (field in onUpdateFields) { + w.line("stmt[$writeObj.${field.name}] = if (stampAutoSet) ${nowExpr(field)} else dto!!.${field.name}") } - append(" }\n") - } - for (field in onUpdateFields) { - append(" stmt[$writeObj.${field.name}] = if (stampAutoSet) ${nowExpr(field)} else dto!!.${field.name}\n") } - append(" }\n\n") + w.blank() } // --- insert (branches on @generation) --- // @autoSet columns are stamped now() by applyAutoSetColumns — a fresh row's onUpdate // column equals its onCreate column, and the dto's value for them is ignored (#203). - append(" /** Insert a $shortName and return it with the persisted primary key. */\n") - append(" open fun insert(dto: $shortName): $shortName = transaction {\n") - appendInsertBody(preserve = false) - append(" }\n\n") + w.doc("Insert a $shortName and return it with the persisted primary key.") + w.block("open fun insert(dto: $shortName): $shortName = transaction {") { insertBody(preserve = false) } + w.blank() // --- insertPreserving (escape hatch; only when the entity declares @autoSet fields) --- if (hasAutoSet) { - append(" /**\n") - append(" * Insert a $shortName writing its `@autoSet` timestamp columns VERBATIM from the dto\n") - append(" * instead of stamping `now()` — the import / restore / replication escape hatch that\n") - append(" * must keep the original timestamps. Primary-key handling matches [insert].\n") - append(" */\n") - append(" open fun insertPreserving(dto: $shortName): $shortName = transaction {\n") - appendInsertBody(preserve = true) - append(" }\n\n") + w.doc( + "Insert a $shortName writing its `@autoSet` timestamp columns VERBATIM from the dto", + "instead of stamping `now()` — the import / restore / replication escape hatch that", + "must keep the original timestamps. Primary-key handling matches [insert].", + ) + w.block("open fun insertPreserving(dto: $shortName): $shortName = transaction {") { insertBody(preserve = true) } + w.blank() } // --- update (full-row, present-non-null) --- // @autoSet onUpdate columns are stamped now(); onCreate columns are SKIPPED entirely — // a full-row update never rewrites created_at from the dto's (possibly stale) value (#203). - append(" /** Overwrite every column of the row (present-non-null merge). Null if no such row. */\n") - append(" open fun update(id: $pkParamType, dto: $shortName): $shortName? = transaction {\n") - append(" val n = $writeObj.update({ $writeObj.$pkFieldName eq id }) {\n") - for (field in scalarFields) { - if (field.name == pkFieldName) continue - // @autoSet columns are owned by applyAutoSetColumns (onUpdate stamped, onCreate - // skipped) — never in the caller-value merge loop. - if (field.name in autoSetNames) continue - // Required fields are non-null in the DTO → write unconditionally (a null-guard would - // be an always-true `-Werror` warning). Optional fields are nullable → guard, so an - // absent value does not clobber the stored one. Matches the controller PATCH fix. - if (KotlinGenUtil.isRequiredField(field)) { - append(" it[$writeObj.${field.name}] = dto.${field.name}\n") - } else { - append(" if (dto.${field.name} != null) it[$writeObj.${field.name}] = dto.${field.name}\n") + w.doc("Overwrite every column of the row (present-non-null merge). Null if no such row.") + w.block("open fun update(id: $pkParamType, dto: $shortName): $shortName? = transaction {") { + w.block("val n = $writeObj.update({ $writeObj.$pkFieldName eq id }) {") { + for (field in scalarFields) { + if (field.name == pkFieldName) continue + // @autoSet columns are owned by applyAutoSetColumns (onUpdate stamped, onCreate + // skipped) — never in the caller-value merge loop. + if (field.name in autoSetNames) continue + // Required fields are non-null in the DTO → write unconditionally (a null-guard would + // be an always-true `-Werror` warning). Optional fields are nullable → guard, so an + // absent value does not clobber the stored one. Matches the controller PATCH fix. + if (KotlinGenUtil.isRequiredField(field)) { + w.line("it[$writeObj.${field.name}] = dto.${field.name}") + } else { + w.line("if (dto.${field.name} != null) it[$writeObj.${field.name}] = dto.${field.name}") + } + } + if (hasOnUpdate) w.line("applyAutoSetColumns(it, includeOnCreate = false)") } + w.line("if (n == 0) null else $readObj.selectAll().where { $readObj.$pkFieldName eq id }.single().let(::rowTo$shortName)") } - if (hasOnUpdate) { - append(" applyAutoSetColumns(it, includeOnCreate = false)\n") - } - append(" }\n") - append(" if (n == 0) null else $readObj.selectAll().where { $readObj.$pkFieldName eq id }.single().let(::rowTo$shortName)\n") - append(" }\n\n") + w.blank() // --- patch (Exposed statement-lambda) --- - append(" /**\n") - append(" * Partial update — the block sets only the columns it names, e.g.\n") - append(" * `repo.patch(id) { it[${writeObj}.] = value }`. A renamed or dropped column is a\n") - append(" * COMPILE error, not a silently skipped write. Null if no such row.\n") + val patchDoc = mutableListOf( + "Partial update — the block sets only the columns it names, e.g.", + "`repo.patch(id) { it[$writeObj.] = value }`. A renamed or dropped column is a", + "COMPILE error, not a silently skipped write. Null if no such row.", + ) if (hasOnUpdate) { - append(" * `@autoSet` onUpdate columns are stamped BEFORE the block runs, so a partial\n") - append(" * update still bumps them even if the block does not name them (#203).\n") + patchDoc += "`@autoSet` onUpdate columns are stamped BEFORE the block runs, so a partial" + patchDoc += "update still bumps them even if the block does not name them (#203)." } - append(" */\n") - append(" open fun patch(id: $pkParamType, block: $writeObj.(UpdateStatement) -> Unit): $shortName? = transaction {\n") - if (hasOnUpdate) { - // Stamp onUpdate first, then let the caller's block win on any column it names. - append(" val n = $writeObj.update({ $writeObj.$pkFieldName eq id }) {\n") - append(" applyAutoSetColumns(it, includeOnCreate = false)\n") - append(" this.block(it)\n") - append(" }\n") - } else { - append(" val n = $writeObj.update({ $writeObj.$pkFieldName eq id }, body = block)\n") + w.doc(*patchDoc.toTypedArray()) + w.block("open fun patch(id: $pkParamType, block: $writeObj.(UpdateStatement) -> Unit): $shortName? = transaction {") { + if (hasOnUpdate) { + // Stamp onUpdate first, then let the caller's block win on any column it names. + w.block("val n = $writeObj.update({ $writeObj.$pkFieldName eq id }) {") { + w.line("applyAutoSetColumns(it, includeOnCreate = false)") + w.line("this.block(it)") + } + } else { + w.line("val n = $writeObj.update({ $writeObj.$pkFieldName eq id }, body = block)") + } + w.line("if (n == 0) null else $readObj.selectAll().where { $readObj.$pkFieldName eq id }.single().let(::rowTo$shortName)") } - append(" if (n == 0) null else $readObj.selectAll().where { $readObj.$pkFieldName eq id }.single().let(::rowTo$shortName)\n") - append(" }\n\n") + w.blank() // --- delete --- - append(" /** Delete by primary key; true if a row was removed. */\n") - append(" open fun delete(id: $pkParamType): Boolean = transaction {\n") - if (api == ExposedApi.V1) { - // issue #390: under 1.x `eq` is a plain top-level import — deleteWhere's lambda - // no longer provides an implicit SqlExpressionBuilder receiver, so the `with(...)` - // wrapper 0.x needed is both unnecessary and unavailable (SqlExpressionBuilder - // is not imported in this file under V1 — see the import block above). - append(" $writeObj.deleteWhere { $writeObj.$pkFieldName eq id } > 0\n") - } else { - // `eq` must resolve through SqlExpressionBuilder inside deleteWhere's receiver (same - // gotcha the controller documents — a bare `Table.pk eq id` is "Unresolved reference: eq"). - append(" $writeObj.deleteWhere { with(SqlExpressionBuilder) { $writeObj.$pkFieldName eq id } } > 0\n") + w.doc("Delete by primary key; true if a row was removed.") + w.block("open fun delete(id: $pkParamType): Boolean = transaction {") { + if (api == ExposedApi.V1) { + // issue #390: under 1.x `eq` is a plain top-level import — deleteWhere's lambda + // no longer provides an implicit SqlExpressionBuilder receiver, so the `with(...)` + // wrapper 0.x needed is both unnecessary and unavailable (SqlExpressionBuilder + // is not imported in this file under V1 — see the import block above). + w.line("$writeObj.deleteWhere { $writeObj.$pkFieldName eq id } > 0") + } else { + // `eq` must resolve through SqlExpressionBuilder inside deleteWhere's receiver (same + // gotcha the controller documents — a bare `Table.pk eq id` is "Unresolved reference: eq"). + w.line("$writeObj.deleteWhere { with(SqlExpressionBuilder) { $writeObj.$pkFieldName eq id } } > 0") + } } - append(" }\n") - - append("}\n") } val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$repoName.kt") - GeneratedFileWriter.write(outFile, src) + GeneratedFileWriter.write(outFile, w.toString()) } /** diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt index 0407e0ae01..71f33057f7 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/writer/KotlinWriter.kt @@ -169,13 +169,13 @@ open class KotlinWriter @JvmOverloads constructor(options: WriterOptions = KOTLI /** * False for a name in a package Kotlin imports by default or in the file's own package. An * aliased import ([importTargets] holds `""`) always needs its line, since the alias is the - * only way the file can say the name. + * only way the file can say the name. A name with no dot is in the root package, which a file + * in a named package reaches only through an import. */ protected open fun needsImport(qualifiedName: String): Boolean { if (qualifiedName.isEmpty()) return true val dot = qualifiedName.lastIndexOf('.') - if (dot < 0) return false - val pkg = qualifiedName.substring(0, dot) + val pkg = if (dot < 0) "" else qualifiedName.substring(0, dot) return pkg !in DEFAULT_IMPORTS && pkg != (packageName ?: "") } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt index a656fad07c..adacc5af2e 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt @@ -1107,7 +1107,7 @@ class KotlinExposedTableGeneratorTest { * instead of `varchar(...)`. The Kotlin data class property type stays `String` (ADR-0037: * `@dbColumnType` is physical-only) — `uuidString`'s custom `ColumnType` converts at * the Kotlin-value boundary, delegating every JDBC/DDL concern to Exposed's own - * `UUIDColumnType` (see `KotlinExposedTableGenerator.uuidStringSupportBlock`'s doc). Previously + * `UUIDColumnType` (see `KotlinExposedTableGenerator.writeUuidStringSupport`'s doc). Previously * this emitted a bare `uuid("col")` — a native `Column` that was self-consistent on the * table alone but mismatched the generated entity/controller's `String` property, which never * compiled once a controller was generated+compiled for such an entity (issue found fixing diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinProjectionExtendsInheritanceTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinProjectionExtendsInheritanceTest.kt index 02558d0c0c..81878f4b80 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinProjectionExtendsInheritanceTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinProjectionExtendsInheritanceTest.kt @@ -13,7 +13,7 @@ import kotlin.test.assertTrue * already inherits `@maxLength` — for: * * - `@dbColumnType=uuid` → `uuidString("col")` (NOT `varchar(col, 36)`, NOT - * a native `uuid(...)` `Column` — see `KotlinExposedTableGenerator.uuidStringSupportBlock`) + * a native `uuid(...)` `Column` — see `KotlinExposedTableGenerator.writeUuidStringSupport`) * - `isArray:true` (string) → `array(...)` (NOT `varchar`/`text`) * - a default (instant/TZ-aware) `field.timestamp` → `instantWithTimeZone(...)` (NOT `datetime`) * - a `field.enum` super → the projection's OWN `Status` enum diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt index 452e2d5b49..44b2bd6415 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt @@ -278,7 +278,7 @@ class KotlinTypeMapperTest { // concern to Exposed's own `UUIDColumnType`), so the column agrees with the generated // entity/controller's `String` property — unlike the old bare `uuid(...)` // (`Column`), which never compiled once a controller was generated for such a - // field (see `KotlinExposedTableGenerator.uuidStringSupportBlock`'s doc). + // field (see `KotlinExposedTableGenerator.writeUuidStringSupport`'s doc). val f = StringField("userId") f.addMetaAttr(StringAttribute.create("dbColumnType", "uuid")) assertEquals("uuidString(\"user_id\")", KotlinTypeMapper.exposedColumnSpec(f)) 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 b25560bc0b..70369ff081 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 @@ -5,12 +5,8 @@ "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinCrossFieldRules.kt": "Lays its output out through KotlinPoet (CodeBlock fragments for cross-field validation, spliced into the entity's init block). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinEntityGenerator.kt": "Lays its output out through KotlinPoet (FileSpec and TypeSpec for the entity data class, its builder and value objects). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinEnumEmitter.kt": "Lays its output out through KotlinPoet (FileSpec for the enum class). It moves to KotlinWriter, and KotlinPoet leaves the build, in W-KT-4.", - "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt": "Builds the Exposed table object, its column types and the jsonb helpers with typed line breaks, and names KotlinPoet types. Converted to KotlinWriter in W-KT-2.", - "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExtractSchemaEmitter.kt": "Builds the extract schema with typed line breaks and indentation, and names KotlinPoet types. Converted to KotlinWriter in W-KT-2.", - "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt": "packageHeader() returns a package line with typed line breaks, for the emitters still built as strings and for owned copies ejected at an earlier version. Removed when the last of those callers moves to KotlinWriter.", + "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/KotlinRelationsGenerator.kt": "Builds the relation helpers with typed line breaks and indentation, and names KotlinPoet types. Converted to KotlinWriter in W-KT-2 with the Exposed table generator.", - "codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRepositoryGenerator.kt": "Builds the repository base with typed line breaks. Converted to KotlinWriter in W-KT-2 with the Exposed table generator it reads and writes through.", "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." diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/EventRepositoryBase.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/EventRepositoryBase.kt index 8b298e5806..906ac32949 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/EventRepositoryBase.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/EventRepositoryBase.kt @@ -7,8 +7,8 @@ import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.UpdateBuilder import org.jetbrains.exposed.sql.statements.UpdateStatement -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update /** * GENERATED — persistence repository base for Event. Do not hand-edit. @@ -17,7 +17,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2). */ open class EventRepositoryBase { - /** Map an Exposed ResultRow to the Event data class. */ open fun rowToEvent(row: ResultRow): Event = Event( id = row[EventTable.id], diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/NoteRepositoryBase.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/NoteRepositoryBase.kt index ed27a4c09f..b7ae1be56a 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/NoteRepositoryBase.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-autoset/acme/events/NoteRepositoryBase.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.UpdateStatement -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update /** * GENERATED — persistence repository base for Note. Do not hand-edit. @@ -16,7 +16,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2). */ open class NoteRepositoryBase { - /** Map an Exposed ResultRow to the Note data class. */ open fun rowToNote(row: ResultRow): Note = Note( id = row[NoteTable.id], diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-bidirectional-fk/acme/blog/PostTable.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-bidirectional-fk/acme/blog/PostTable.kt index 468df6a247..aafb78557e 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-bidirectional-fk/acme/blog/PostTable.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-bidirectional-fk/acme/blog/PostTable.kt @@ -1,7 +1,7 @@ package acme.blog -import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.ReferenceOption +import org.jetbrains.exposed.sql.Table /** GENERATED — do not hand-edit. Regenerated from metadata. */ object PostTable : Table("posts") { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorRepositoryBase.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorRepositoryBase.kt index d2c7ff20ad..e989983837 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorRepositoryBase.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-controller/acme/blog/AuthorRepositoryBase.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.UpdateStatement -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update /** * GENERATED — persistence repository base for Author. Do not hand-edit. @@ -16,7 +16,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2). */ open class AuthorRepositoryBase { - /** Map an Exposed ResultRow to the Author data class. */ open fun rowToAuthor(row: ResultRow): Author = Author( id = row[AuthorTable.id], diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaPortableColumnTypes.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaPortableColumnTypes.kt index 8eb013dce6..1bde62cbd7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaPortableColumnTypes.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter-wire-string/acme/catalog/MetaPortableColumnTypes.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.ColumnType import org.jetbrains.exposed.sql.DecimalColumnType import org.jetbrains.exposed.sql.Table -import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.UUIDColumnType +import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.vendors.currentDialect private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) @@ -103,4 +103,3 @@ internal class MetaDecimalArrayColumnType : ColumnType>() { /** Column builder for an `isArray` `field.decimal`: a `Column>`. */ internal fun Table.portableDecimalArray(name: String): Column> = registerColumn(name, MetaDecimalArrayColumnType()) - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaPortableColumnTypes.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaPortableColumnTypes.kt index 8eb013dce6..1bde62cbd7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaPortableColumnTypes.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-decimal-float-filter/acme/catalog/MetaPortableColumnTypes.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.ColumnType import org.jetbrains.exposed.sql.DecimalColumnType import org.jetbrains.exposed.sql.Table -import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.UUIDColumnType +import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.vendors.currentDialect private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) @@ -103,4 +103,3 @@ internal class MetaDecimalArrayColumnType : ColumnType>() { /** Column builder for an `isArray` `field.decimal`: a `Column>`. */ internal fun Table.portableDecimalArray(name: String): Column> = registerColumn(name, MetaDecimalArrayColumnType()) - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/AuthorRepositoryBase.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/AuthorRepositoryBase.kt index 0178ef76d8..63eb7764b0 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/AuthorRepositoryBase.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/AuthorRepositoryBase.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.UpdateStatement -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update /** * GENERATED — persistence repository base for Author. Do not hand-edit. @@ -16,7 +16,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2). */ open class AuthorRepositoryBase { - /** Map an Exposed ResultRow to the Author data class. */ open fun rowToAuthor(row: ResultRow): Author = Author( id = row[AuthorTable.id], diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostRepositoryBase.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostRepositoryBase.kt index 9270e8318d..56a2b32ff5 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostRepositoryBase.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostRepositoryBase.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.UpdateStatement -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update /** * GENERATED — persistence repository base for Post. Do not hand-edit. @@ -16,7 +16,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2). */ open class PostRepositoryBase { - /** Map an Exposed ResultRow to the Post data class. */ open fun rowToPost(row: ResultRow): Post = Post( id = row[PostTable.id], diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostTable.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostTable.kt index b5e0080e6d..0e75a9cdb0 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostTable.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-fk/acme/blog/PostTable.kt @@ -1,7 +1,7 @@ package acme.blog -import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.ReferenceOption +import org.jetbrains.exposed.sql.Table /** GENERATED — do not hand-edit. Regenerated from metadata. */ object PostTable : Table("posts") { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage-wire-omit/acme/commerce/MetaJsonbMapper.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage-wire-omit/acme/commerce/MetaJsonbMapper.kt index dd52333829..cbdf3d5043 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage-wire-omit/acme/commerce/MetaJsonbMapper.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage-wire-omit/acme/commerce/MetaJsonbMapper.kt @@ -17,4 +17,3 @@ internal val metaJsonbMapper: com.fasterxml.jackson.databind.ObjectMapper = .addModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule()) .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .build() - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage/acme/commerce/MetaJsonbMapper.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage/acme/commerce/MetaJsonbMapper.kt index dd52333829..cbdf3d5043 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage/acme/commerce/MetaJsonbMapper.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-storage/acme/commerce/MetaJsonbMapper.kt @@ -17,4 +17,3 @@ internal val metaJsonbMapper: com.fasterxml.jackson.databind.ObjectMapper = .addModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule()) .disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .build() - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineTable.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineTable.kt index 74aeca990b..79d1a838f5 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineTable.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthLineTable.kt @@ -1,7 +1,7 @@ package acme.auth -import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.ReferenceOption +import org.jetbrains.exposed.sql.Table /** GENERATED — do not hand-edit. Regenerated from metadata. */ object AuthLineTable : Table("auth_lines") { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaPortableColumnTypes.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaPortableColumnTypes.kt index eda958203e..5d7fef3e7a 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaPortableColumnTypes.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/MetaPortableColumnTypes.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.ColumnType import org.jetbrains.exposed.sql.DecimalColumnType import org.jetbrains.exposed.sql.Table -import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.UUIDColumnType +import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import org.jetbrains.exposed.sql.vendors.currentDialect private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) @@ -103,4 +103,3 @@ internal class MetaDecimalArrayColumnType : ColumnType>() { /** Column builder for an `isArray` `field.decimal`: a `Column>`. */ internal fun Table.portableDecimalArray(name: String): Column> = registerColumn(name, MetaDecimalArrayColumnType()) - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/AuthorRepositoryBase.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/AuthorRepositoryBase.kt index d1413a5ae9..f2de4b7aa6 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/AuthorRepositoryBase.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/AuthorRepositoryBase.kt @@ -6,8 +6,8 @@ import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.statements.UpdateStatement -import org.jetbrains.exposed.sql.update import org.jetbrains.exposed.sql.transactions.transaction +import org.jetbrains.exposed.sql.update /** * GENERATED — persistence repository base for Author. Do not hand-edit. @@ -16,7 +16,6 @@ import org.jetbrains.exposed.sql.transactions.transaction * would create an ambiguous bean — wiring is the consumer's, per FR-035 §8.2). */ open class AuthorRepositoryBase { - /** Map an Exposed ResultRow to the Author data class. */ open fun rowToAuthor(row: ResultRow): Author = Author( id = row[AuthorTable.id], diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetaInstantWithTimeZoneColumnType.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetaInstantWithTimeZoneColumnType.kt index 62ad205d30..7db9c6f546 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetaInstantWithTimeZoneColumnType.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/single-entity-primitives/acme/demo/MetaInstantWithTimeZoneColumnType.kt @@ -43,4 +43,3 @@ internal class MetaInstantWithTimeZoneColumnType : */ internal fun Table.instantWithTimeZone(name: String): Column = registerColumn(name, MetaInstantWithTimeZoneColumnType()) - diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/OpinionOutputPayloadExtracted.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/OpinionOutputPayloadExtracted.kt index aca6c954f7..e7eab2a32b 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/OpinionOutputPayloadExtracted.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-fr010/acme/ai/OpinionOutputPayloadExtracted.kt @@ -1,4 +1,5 @@ // GENERATED — DO NOT EDIT — lenient extraction mirror of value object `acme::ai::OpinionOutputPayload` + package acme.ai import com.metaobjects.render.extract.ExtractMap @@ -12,8 +13,9 @@ data class OpinionOutputPayloadExtracted( val confidence: String? = null, val note: String? = null, ) { - - /** The strict [OpinionOutputPayload]. Call only once the extract report shows no lost or malformed required field. */ + /** + * The strict [OpinionOutputPayload]. Call only once the extract report shows no lost or malformed required field. + */ fun toStrict(): OpinionOutputPayload = OpinionOutputPayload( text = text!!, confidence = acme.ai.OpinionOutputPayloadConfidence.valueOf(confidence!!), @@ -21,7 +23,6 @@ data class OpinionOutputPayloadExtracted( ) companion object { - /** Map an assembled ValueObject (a Map) onto the typed mirror; null-tolerant. */ @JvmStatic fun fromMap(d: Map?): OpinionOutputPayloadExtracted? { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/GreetingExtracted.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/GreetingExtracted.kt index cbf63d58ef..aa7a74079a 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/GreetingExtracted.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/template-output-parser/acme/ai/GreetingExtracted.kt @@ -1,4 +1,5 @@ // GENERATED — DO NOT EDIT — lenient extraction mirror of value object `acme::ai::Greeting` + package acme.ai import com.metaobjects.render.extract.ExtractMap @@ -7,17 +8,13 @@ import com.metaobjects.render.extract.ExtractMap * All-nullable mirror of [Greeting] for tolerant extraction: a partial model * reply still maps. [toStrict] converts it once no `@required` field was lost or malformed. */ -data class GreetingExtracted( - val text: String? = null, -) { - +data class GreetingExtracted(val text: String? = null) { /** The strict [Greeting]. Call only once the extract report shows no lost or malformed required field. */ fun toStrict(): Greeting = Greeting( text = text, ) companion object { - /** Map an assembled ValueObject (a Map) onto the typed mirror; null-tolerant. */ @JvmStatic fun fromMap(d: Map?): GreetingExtracted? { diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/KotlinCodegenMatchesReferenceTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/KotlinCodegenMatchesReferenceTest.kt index 3057078a35..d08df8785a 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/KotlinCodegenMatchesReferenceTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/KotlinCodegenMatchesReferenceTest.kt @@ -92,7 +92,7 @@ internal class KotlinCodegenMatchesReferenceTest { // type (NOT a bare `uuid(...)` `Column`: ADR-0037 keeps the escape hatch's logical // type `String`, matching the generated entity/controller — found fixing // AssetController.kt's pre-existing compile defect, see KotlinExposedTableGenerator's - // `uuidStringSupportBlock`). Verifies the generator emits the native families the + // `writeUuidStringSupport`). Verifies the generator emits the native families the // hand-written reference AssetTable carries for id/ownerId/payload/recordedAt (AssetTable // itself intentionally still uses native `uuid("externalId")` for its OWN purpose — the // SP-H roundtrip harness reads/normalizes a `java.util.UUID` directly and never passes diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AssetTable.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AssetTable.kt index 010743bac2..669b2a1007 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AssetTable.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AssetTable.kt @@ -35,7 +35,7 @@ object AssetTable : Table("assets") { val ownerId = uuid("ownerId") // `field.string` + `@dbColumnType:uuid` — a DELIBERATE divergence from what the generator // now emits (`uuidString("externalId")`, a `Column`; see - // KotlinExposedTableGenerator.uuidStringSupportBlock's doc). That change exists to agree + // KotlinExposedTableGenerator.writeUuidStringSupport's doc). That change exists to agree // with a GENERATED entity/controller's `String` property (ADR-0037) — a concern this // hand-written table never has, since its only caller is this file's own runner, which // reads/writes a `java.util.UUID` directly and normalizes it itself (lowercases it diff --git a/spec/code-writer.md b/spec/code-writer.md index cd1c85de2c..ba843226a2 100644 --- a/spec/code-writer.md +++ b/spec/code-writer.md @@ -190,7 +190,9 @@ conventions write them. returns the name to write, its last segment. `use("pkg.Name", alias)` records `import pkg.Name as alias` and returns the alias. A name in a package Kotlin imports by default (`kotlin`, `kotlin.collections`, `kotlin.io`, `java.lang` and the rest of the language's default - imports), or in the file's own package, prints no line. An aliased import always prints. + imports), or in the file's own package, prints no line. A name with no dot is in the root + package: it prints a line unless the file is in the root package too. An aliased import always + prints. - **Order.** One group, in code-unit order of what follows `import `, with no blank lines. A name used twice is imported once. - One local name imported from two names is **`ERR_WRITER_IMPORT_CONFLICT`**. From d59d9bc5d4e74084c99b7b7795b8e375c68077d7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 26 Nov 2026 05:24:09 -0500 Subject: [PATCH 2/3] no-mistakes(test): Add Kotlin writer case for root-package file imports --- CHANGELOG.md | 2 +- docs/CONFORMANCE.md | 2 +- .../kotlin-imports-root-package-same-file.json | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 fixtures/writer-conformance/cases/kotlin-imports-root-package-same-file.json diff --git a/CHANGELOG.md b/CHANGELOG.md index aa22da2332..c513150584 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1647,7 +1647,7 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru file, a one-property extract mirror on one line, a KDoc too long for one line written as a block, and a blank line after the extract mirror's header comment. `KotlinWriter` now imports a root-package name (one with no dot) into a file in a named package, as the generators it - replaced did; a new `kotlin` writer case pins it. The support files' text builders + replaced did; two new `kotlin` writer cases pin it. The support files' text builders (`instantTzSupportBlock`, `inetUriSupportFileImports` and the rest) became writer functions (`writeInstantTzSupport` and its siblings); an owned copy ejected at an earlier version carries its own and still compiles (`EjectedAtBaseGeneratorsCompatTest`). diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 9ffe8164d7..f222113fe5 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -71,7 +71,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | ✓ (every case but the three-way merge one) | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 87 cases (31 core + 10 TypeScript + 9 Java + 11 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 88 cases (31 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | — | diff --git a/fixtures/writer-conformance/cases/kotlin-imports-root-package-same-file.json b/fixtures/writer-conformance/cases/kotlin-imports-root-package-same-file.json new file mode 100644 index 0000000000..36fc97242c --- /dev/null +++ b/fixtures/writer-conformance/cases/kotlin-imports-root-package-same-file.json @@ -0,0 +1,17 @@ +{ + "description": "A file in the root package does not import a root-package name (one with no dot): Kotlin sees it unqualified from another root-package file.", + "dialect": "kotlin", + "ops": [ + [ + "use", + "RootTable" + ], + [ + "line", + "val t = RootTable" + ] + ], + "expected": [ + "val t = RootTable" + ] +} From 78755b30765ab1d4c662ea2d070ab53030d8e3a2 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 26 Nov 2026 05:33:32 -0500 Subject: [PATCH 3/3] no-mistakes(document): Docs current for W-KT-2; one stale generator count in docs/ports/kotlin.md replaced with a pointer to ADR-0063 and the ratchet allowlist. --- docs/ports/kotlin.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 89e3d43a9e..953d4e48fe 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -16,7 +16,7 @@ classes. Two modules: -- **`metaobjects-codegen-kotlin`** — 16 KotlinPoet-based generators. +- **`metaobjects-codegen-kotlin`** — the generators; most lay their output out through `KotlinWriter` (ADR-0063), and the layout ratchet's allowlist names the ones still on KotlinPoet. - **`metaobjects-metadata-ktx`** — thin Kotlin facade over the Java loader + render engine for idiomatic Kotlin runtime use.