Skip to content

Commit 351362c

Browse files
committed
feat(metamodel): ADR-0036 Wave 3 JVM — field.uri, field.inet subtypes + @stringformat (Java + Kotlin)
Replicate the TS reference (ADR-0036 decision #2 / ADR-0037) Wave 3 on the shared JVM metadata + the Java (codegen-spring) and Kotlin (codegen-kotlin) codegen ports, byte-matching the cross-port goldens (expected-registry.json, field-uri-inet-stringformat conformance fixture — neither modified here). Metadata (shared by Java + Kotlin): - field.uri — a URI/URL string. Bare scalar inheriting field.base; native JVM binding java.net.URI; DB column text. New UriField class + registration. - field.inet — an IP-address string (v4/v6). Bare scalar; native JVM binding java.net.InetAddress; DB column Postgres-native inet. New InetField class. - @stringformat on field.string — closed {email|hostname} string-typed attr (mirrors @maxlength registration). allowedValues + description sourced from spec/metamodel/field.json via applySpecDescriptions, so both ports' registry manifests byte-match the golden with no hand-written descriptions. - FilterOps op-bands: uri = string band (incl. like); inet = uuid band (no like/ordering), in canonical subtype order after uuid. Codegen — Java (codegen-spring): - SpringTypeMapper: field.uri → java.net.URI, field.inet → java.net.InetAddress. - SpringDtoGenerator: @stringformat:email → Jakarta @Email; hostname → a codegen-owned canonical DNS-hostname @pattern (not author validator.regex). Codegen — Kotlin (codegen-kotlin): - KotlinTypeMapper: field.uri → java.net.URI + file-local uriColumn(...) Exposed column; field.inet → java.net.InetAddress + inetColumn(...). Both backed by a package-shared MetaInetUriColumnType.kt support file (internal custom ColumnType<URI> over text + ColumnType<InetAddress> over native inet), emitted once per package — mirrors the Wave 2 MetaInstantWithTimeZoneColumnType pattern. - KotlinEntityGenerator: @stringformat:email → @field:Email; hostname → the same canonical @field:Pattern hostname check (byte-identical regex to the Spring port). OMDB (runtime persistence JDBC seam): - field.uri ⇄ StringCodec (text column). field.inet ⇄ new InetCodec, binding the String via setObject(.., Types.OTHER) so the driver coerces it into the native inet column (mirrors UuidCodec); read back as String. Tests: SpringTypeMapperTest (+4: uri/inet type mapping, @stringformat email/hostname validation), KotlinTypeMapperTest (+2), KotlinExposedTableGeneratorTest (+1: custom columns + shared support file). Both registry-conformance byte-matches green; the new metamodel conformance fixture loads under strict mode in both ports. The persistence-conformance roundtrip corpus does not yet carry uri/inet (the TS reference did not add them), so Testcontainers roundtrips are not exercised for these subtypes — CI-gated/not-applicable for this wave. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GF9xLEQZaPus5Y6opk398n
1 parent 4b90500 commit 351362c

14 files changed

Lines changed: 571 additions & 0 deletions

File tree

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,22 @@ open class KotlinEntityGenerator : MultiFileDirectGeneratorBase<MetaObject>() {
327327
if (min != null || max != null) out.add(sizeAnnotation(min, max))
328328
}
329329

330+
// ADR-0036/0037 Wave 3 — @stringFormat on a plain string field. The canonical
331+
// matcher per format lives HERE in codegen (NOT author validator.regex), since
332+
// cross-language regex engines diverge. email → @field:Email; hostname → a
333+
// canonical DNS-hostname @field:Pattern check.
334+
if (isString && !isArray && field.hasMetaAttr(StringField.ATTR_STRING_FORMAT)) {
335+
when (field.getMetaAttr(StringField.ATTR_STRING_FORMAT).value?.toString()?.trim()) {
336+
StringField.STRING_FORMAT_EMAIL -> out.add(constraint(EMAIL))
337+
StringField.STRING_FORMAT_HOSTNAME -> out.add(
338+
AnnotationSpec.builder(PATTERN)
339+
.useSiteTarget(AnnotationSpec.UseSiteTarget.FIELD)
340+
.addMember("regexp = %S", HOSTNAME_REGEX)
341+
.build()
342+
)
343+
}
344+
}
345+
330346
return out
331347
}
332348

@@ -382,6 +398,16 @@ open class KotlinEntityGenerator : MultiFileDirectGeneratorBase<MetaObject>() {
382398
val PATTERN = ClassName(JAKARTA_CONSTRAINTS, "Pattern")
383399
val MIN = ClassName(JAKARTA_CONSTRAINTS, "Min")
384400
val MAX = ClassName(JAKARTA_CONSTRAINTS, "Max")
401+
val EMAIL = ClassName(JAKARTA_CONSTRAINTS, "Email")
402+
403+
/**
404+
* Canonical DNS-hostname matcher for `@stringFormat: hostname` (ADR-0036/0037 Wave 3).
405+
* Codegen-owned (NOT author `validator.regex`) — one or more dot-separated labels, each
406+
* 1–63 chars of alphanumerics/hyphens not starting/ending with a hyphen. Byte-identical
407+
* to the Spring port's `SpringDtoGenerator.HOSTNAME_REGEX`.
408+
*/
409+
const val HOSTNAME_REGEX =
410+
"^(?=.{1,253}\$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*\$"
385411
}
386412

387413
// === MultiFileDirectGeneratorBase abstract-method stubs ====================

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

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,13 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase<MetaObject
6363
// redeclare the top-level support class/extension and fail to compile.
6464
val packagesNeedingInstantTzHelper = sortedSetOf<String>()
6565

66+
// Packages that emit at least one table carrying a `field.uri` or `field.inet`
67+
// column (ADR-0036/0037 Wave 3). Each such package gets ONE shared
68+
// `MetaInetUriColumnType.kt` support file (the custom `Column<URI>`/`Column<InetAddress>`
69+
// column types + the `uriColumn(...)`/`inetColumn(...)` builder extensions), emitted in
70+
// pass 3 — same multi-table-per-package sharing rationale as the instant-tz helper.
71+
val packagesNeedingInetUriHelper = sortedSetOf<String>()
72+
6673
// Pass 2: emit one Table per entity using its own metadata + the
6774
// inbound FKs accumulated in Pass 1.
6875
// FR-024 (ADR-0028): object.projection is emitted too — a projection with
@@ -100,6 +107,12 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase<MetaObject
100107
if (usedInstantTzHelper) {
101108
packagesNeedingInstantTzHelper += PackageMapping.splitFqn(entity.name).first
102109
}
110+
// ADR-0036/0037 Wave 3: does this table carry a `field.uri`/`field.inet` column?
111+
// Walk direct fields AND flattened object sub-fields — the same two surfaces that
112+
// contribute columns (mirrors the instant-tz detection inside emit()).
113+
if (entityNeedsInetUriHelper(entity, loader)) {
114+
packagesNeedingInetUriHelper += PackageMapping.splitFqn(entity.name).first
115+
}
103116
}
104117

105118
// Pass 3: emit ONE shared `MetaInstantWithTimeZoneColumnType.kt` per package
@@ -110,6 +123,55 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase<MetaObject
110123
for (pkg in packagesNeedingInstantTzHelper) {
111124
emitInstantTzSupportFile(pkg, outRoot)
112125
}
126+
127+
// Pass 3b (ADR-0036/0037 Wave 3): emit ONE shared `MetaInetUriColumnType.kt` per
128+
// package that has at least one `field.uri`/`field.inet` column. Same `internal`
129+
// per-package sharing rationale as the instant-tz helper above.
130+
for (pkg in packagesNeedingInetUriHelper) {
131+
emitInetUriSupportFile(pkg, outRoot)
132+
}
133+
}
134+
135+
/**
136+
* True iff [entity] carries at least one `field.uri`/`field.inet` column — on a direct
137+
* field OR a flattened `object.value` sub-field. Mirrors the instant-tz detection inside
138+
* [emit] (which walks the same two surfaces).
139+
*/
140+
private fun entityNeedsInetUriHelper(entity: MetaObject, loader: MetaDataLoader): Boolean {
141+
if (entity.metaFields.any { it !is ObjectField && KotlinTypeMapper.usesInetUriHelper(it) }) {
142+
return true
143+
}
144+
for (field in entity.metaFields) {
145+
if (field !is ObjectField) continue
146+
if (readStorage(field) != STORAGE_FLATTENED) continue
147+
val ref = readObjectRef(field) ?: continue
148+
val target = KotlinGenUtil.resolveObjectByShortOrFqn(loader, ref) ?: continue
149+
if (target.metaFields.any { KotlinTypeMapper.usesInetUriHelper(it) }) return true
150+
}
151+
return false
152+
}
153+
154+
/**
155+
* Emit the per-package `MetaInetUriColumnType.kt` support file (ADR-0036/0037 Wave 3):
156+
* `internal` custom Exposed column types for `field.uri` (a `Column<java.net.URI>` over
157+
* plain `text`) and `field.inet` (a `Column<java.net.InetAddress>` over the Postgres-native
158+
* `inet` type), plus the `Table.uriColumn(name)` / `Table.inetColumn(name)` column-builder
159+
* extensions the generated tables call. `internal` keeps it package+module-private while
160+
* every `*Table.kt` in the package shares the one declaration.
161+
*/
162+
private fun emitInetUriSupportFile(pkg: String, outRoot: Path) {
163+
val body = buildString {
164+
if (pkg.isNotEmpty()) {
165+
append("package $pkg\n\n")
166+
}
167+
append(INET_URI_SUPPORT_FILE_IMPORTS)
168+
append("\n")
169+
append(INET_URI_SUPPORT_BLOCK)
170+
append("\n")
171+
}
172+
val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve("$INET_URI_SUPPORT_FILE_NAME.kt")
173+
outFile.parent?.let { Files.createDirectories(it) }
174+
Files.writeString(outFile, body)
113175
}
114176

115177
/**
@@ -627,6 +689,87 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase<MetaObject
627689
|internal fun Table.instantWithTimeZone(name: String): Column<Instant> =
628690
| registerColumn(name, MetaInstantWithTimeZoneColumnType())
629691
|""".trimMargin()
692+
693+
/**
694+
* File name (sans `.kt`) of the per-package support file emitted for `field.uri` /
695+
* `field.inet` columns (ADR-0036/0037 Wave 3). One per package that has ≥1 such column.
696+
*/
697+
const val INET_URI_SUPPORT_FILE_NAME = "MetaInetUriColumnType"
698+
699+
/** Imports for the per-package [INET_URI_SUPPORT_BLOCK] support file. */
700+
val INET_URI_SUPPORT_FILE_IMPORTS: String = """
701+
|import java.net.InetAddress
702+
|import java.net.URI
703+
|import org.jetbrains.exposed.sql.Column
704+
|import org.jetbrains.exposed.sql.ColumnType
705+
|import org.jetbrains.exposed.sql.Table
706+
|import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi
707+
|import org.jetbrains.exposed.sql.vendors.currentDialect
708+
|""".trimMargin()
709+
710+
/**
711+
* Shared support body emitted ONCE PER PACKAGE (into [INET_URI_SUPPORT_FILE_NAME].kt)
712+
* for any package with at least one `field.uri` / `field.inet` column. Defines two
713+
* `internal` custom column types + their `Table` column-builder extensions:
714+
*
715+
* - `MetaUriColumnType` — a `ColumnType<java.net.URI>` over plain `text` (Postgres has
716+
* no uri type). Reads the JDBC string and parses it to a `URI`; writes the `URI`'s
717+
* string form. Yields `Column<URI>` so the column matches the data-class property.
718+
* - `MetaInetColumnType` — a `ColumnType<java.net.InetAddress>` over the Postgres-native
719+
* `inet` type. Reads the JDBC string and resolves it to an `InetAddress`; binds the
720+
* address' host-literal string (`getHostAddress`) so the JDBC driver routes it to the
721+
* native `inet` column.
722+
*
723+
* Both are `internal` so every `*Table.kt` in the package shares the one declaration.
724+
* The `$` lines below carry no Kotlin string templates — emitted verbatim.
725+
*/
726+
val INET_URI_SUPPORT_BLOCK: String = """
727+
|/**
728+
| * GENERATED — do not hand-edit.
729+
| * Custom Exposed column type for `field.uri`: a `Column<java.net.URI>` whose SQL DDL
730+
| * is plain `text` (Postgres has no uri type). The native URI binding matches the data
731+
| * class property; the value persists as its string form.
732+
| */
733+
|internal class MetaUriColumnType : ColumnType<URI>() {
734+
| override fun sqlType(): String = currentDialect.dataTypeProvider.textType()
735+
| override fun valueFromDB(value: Any): URI = when (value) {
736+
| is URI -> value
737+
| else -> URI.create(value.toString())
738+
| }
739+
| override fun notNullValueToDB(value: URI): Any = value.toString()
740+
| override fun nonNullValueToString(value: URI): String = "'${'$'}value'"
741+
|}
742+
|
743+
|/** Column builder for `field.uri`: a `Column<java.net.URI>` over a `text` column. */
744+
|internal fun Table.uriColumn(name: String): Column<URI> =
745+
| registerColumn(name, MetaUriColumnType())
746+
|
747+
|/**
748+
| * GENERATED — do not hand-edit.
749+
| * Custom Exposed column type for `field.inet`: a `Column<java.net.InetAddress>` whose
750+
| * SQL DDL is the Postgres-native `inet`. The native InetAddress binding matches the data
751+
| * class property; the value binds/reads as its host-literal string.
752+
| */
753+
|internal class MetaInetColumnType : ColumnType<InetAddress>() {
754+
| override fun sqlType(): String = "inet"
755+
| override fun valueFromDB(value: Any): InetAddress = when (value) {
756+
| is InetAddress -> value
757+
| else -> InetAddress.getByName(value.toString())
758+
| }
759+
| override fun notNullValueToDB(value: InetAddress): Any = value.hostAddress
760+
| override fun nonNullValueToString(value: InetAddress): String = "'${'$'}{value.hostAddress}'"
761+
| override fun setParameter(stmt: PreparedStatementApi, index: Int, value: Any?) {
762+
| // Bind as a string and let the Postgres JDBC driver coerce it to the native
763+
| // `inet` column.
764+
| val v = if (value is InetAddress) value.hostAddress else value
765+
| stmt[index] = v
766+
| }
767+
|}
768+
|
769+
|/** Column builder for `field.inet`: a `Column<java.net.InetAddress>` over an `inet` column. */
770+
|internal fun Table.inetColumn(name: String): Column<InetAddress> =
771+
| registerColumn(name, MetaInetColumnType())
772+
|""".trimMargin()
630773
}
631774

632775
// === FK column emission from relationship.composition ====================

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import com.metaobjects.field.StringField
1616
import com.metaobjects.field.TimeField
1717
import com.metaobjects.field.TimestampField
1818
import com.metaobjects.field.UuidField
19+
import com.metaobjects.field.UriField
20+
import com.metaobjects.field.InetField
1921
import com.metaobjects.`object`.MetaObject
2022
import com.squareup.kotlinpoet.ANY
2123
import com.squareup.kotlinpoet.BOOLEAN
@@ -134,6 +136,26 @@ object KotlinTypeMapper {
134136
*/
135137
const val EXPOSED_INSTANT_TZ_FN = "instantWithTimeZone"
136138

139+
/**
140+
* Name of the generated, file-local Exposed extension function emitted for a
141+
* [UriField] (ADR-0036/0037 Wave 3). Returns a `Column<java.net.URI>` whose
142+
* `sqlType()` is `text` (Postgres has no uri type), so the column type MATCHES the
143+
* `java.net.URI` data-class property while persisting plain text.
144+
* [KotlinExposedTableGenerator] emits the supporting `ColumnType<URI>` + this extension
145+
* into the package-shared [MetaInetUriColumnType] support file.
146+
*/
147+
const val EXPOSED_URI_FN = "uriColumn"
148+
149+
/**
150+
* Name of the generated, file-local Exposed extension function emitted for an
151+
* [InetField] (ADR-0036/0037 Wave 3). Returns a `Column<java.net.InetAddress>` whose
152+
* `sqlType()` is the Postgres-native `inet`, so the column type MATCHES the
153+
* `java.net.InetAddress` data-class property while using the native inet column.
154+
* [KotlinExposedTableGenerator] emits the supporting `ColumnType<InetAddress>` + this
155+
* extension into the package-shared [MetaInetUriColumnType] support file.
156+
*/
157+
const val EXPOSED_INET_FN = "inetColumn"
158+
137159
/**
138160
* Compute the generated Kotlin enum-class name for an [EnumField] hung off [entity].
139161
*
@@ -245,6 +267,14 @@ object KotlinTypeMapper {
245267
// field.string is the separate physical escape hatch and keeps the String property —
246268
// handled by the StringField arm, not here.
247269
is UuidField -> ClassName("java.util", "UUID")
270+
// field.uri → native java.net.URI property (ADR-0036/0037 Wave 3). The DB column is
271+
// plain text (Postgres has no uri type); the file-local `uriColumn(...)` extension
272+
// gives a `Column<URI>` so the property and column types match.
273+
is UriField -> ClassName("java.net", "URI")
274+
// field.inet → native java.net.InetAddress property (ADR-0036/0037 Wave 3). The DB
275+
// column is the Postgres-native inet type; the file-local `inetColumn(...)` extension
276+
// gives a `Column<InetAddress>`.
277+
is InetField -> ClassName("java.net", "InetAddress")
248278
// field.map → an open-keyed Map<String, V> stored in a single jsonb column.
249279
// Keys are always String. The value type is the scalar named by @valueType,
250280
// or (for an @objectRef map) the referenced VO — which needs the loader to
@@ -453,6 +483,14 @@ object KotlinTypeMapper {
453483
is UuidField ->
454484
if (isArrayResolved(field)) "array<java.util.UUID>(\"$colName\", org.jetbrains.exposed.sql.UUIDColumnType())"
455485
else "uuid(\"$colName\")"
486+
// field.uri → file-local `uriColumn(...)` extension: a `Column<java.net.URI>` whose
487+
// DDL is plain `text` (Postgres has no uri type). The helper lives in the package-shared
488+
// MetaInetUriColumnType.kt support file (emitted once per package).
489+
is UriField -> "$EXPOSED_URI_FN(\"$colName\")"
490+
// field.inet → file-local `inetColumn(...)` extension: a `Column<java.net.InetAddress>`
491+
// whose DDL is the Postgres-native `inet`. The helper lives in the package-shared
492+
// MetaInetUriColumnType.kt support file (emitted once per package).
493+
is InetField -> "$EXPOSED_INET_FN(\"$colName\")"
456494
// field.map → a single Postgres `JSONB` column holding the JSON object. Same
457495
// emission as a `field.object` jsonb column (the typed-object JSONB path) — the
458496
// Exposed `jsonb(name, encoder, decoder)` extension with kotlinx.serialization
@@ -519,6 +557,16 @@ object KotlinTypeMapper {
519557
fun usesInstantWithTimeZone(field: MetaField<*>): Boolean =
520558
field is TimestampField && !localTimeOptIn(field)
521559

560+
/**
561+
* True iff [field] needs the package-shared `MetaInetUriColumnType.kt` support file —
562+
* i.e. it is a [UriField] (custom `Column<URI>` over `text`) or an [InetField] (custom
563+
* `Column<InetAddress>` over the Postgres-native `inet` type). ADR-0036/0037 Wave 3.
564+
* [KotlinExposedTableGenerator] uses this to decide whether a package needs the support
565+
* file (one `uriColumn`/`inetColumn` extension declaration shared across its tables).
566+
*/
567+
fun usesInetUriHelper(field: MetaField<*>): Boolean =
568+
field is UriField || field is InetField
569+
522570
/**
523571
* Best-effort read of a named boolean attribute on [field], resolved THROUGH the `extends`
524572
* super-field chain (own value wins). Returns false when absent/unparseable. Used for the

‎server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,46 @@ class KotlinExposedTableGeneratorTest {
4343
}
4444
}
4545

46+
@Test fun `field uri and field inet emit custom columns and the shared support file`() {
47+
// ADR-0036/0037 Wave 3: a `field.uri` → `uriColumn(...)` (Column<URI> over text);
48+
// a `field.inet` → `inetColumn(...)` (Column<InetAddress> over native inet); both
49+
// backed by the package-shared MetaInetUriColumnType.kt support file.
50+
val fixture = """{
51+
"metadata.root": { "package": "acme::demo", "children": [
52+
{ "object.entity": { "name": "Endpoint", "children": [
53+
{ "field.long": { "name": "id" } },
54+
{ "field.uri": { "name": "webhookUrl" } },
55+
{ "field.inet": { "name": "sourceIp" } },
56+
{ "source.rdb": { "@table": "endpoints" } },
57+
{ "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } }
58+
] } }
59+
] }
60+
}""".trimIndent()
61+
val outDir = Files.createTempDirectory("ktbl-ineturi-")
62+
try {
63+
val gen = KotlinExposedTableGenerator()
64+
gen.setArgs(mapOf("outputDir" to outDir.toString()))
65+
gen.execute(loadString("test", fixture))
66+
67+
val table = outDir.resolve("acme/demo/EndpointTable.kt")
68+
assertTrue(Files.exists(table), "expected $table")
69+
val src = Files.readString(table)
70+
assertTrue("val webhookUrl = uriColumn(\"webhook_url\")" in src, src)
71+
assertTrue("val sourceIp = inetColumn(\"source_ip\")" in src, src)
72+
73+
val support = outDir.resolve("acme/demo/MetaInetUriColumnType.kt")
74+
assertTrue(Files.exists(support), "expected shared support file $support")
75+
val sup = Files.readString(support)
76+
assertTrue("internal class MetaUriColumnType : ColumnType<URI>()" in sup, sup)
77+
assertTrue("internal class MetaInetColumnType : ColumnType<InetAddress>()" in sup, sup)
78+
assertTrue("override fun sqlType(): String = \"inet\"" in sup, sup)
79+
assertTrue("internal fun Table.uriColumn(name: String): Column<URI>" in sup, sup)
80+
assertTrue("internal fun Table.inetColumn(name: String): Column<InetAddress>" in sup, sup)
81+
} finally {
82+
outDir.toFile().deleteRecursively()
83+
}
84+
}
85+
4686
@Test fun `skips entities without source rdb child`() {
4787
val noSource = """{
4888
"metadata.root": { "package": "x", "children": [

0 commit comments

Comments
 (0)