|
| 1 | +package com.metaobjects.generator.kotlin |
| 2 | + |
| 3 | +import com.metaobjects.generator.GeneratorIOWriter |
| 4 | +import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase |
| 5 | +import com.metaobjects.identity.MetaIdentity |
| 6 | +import com.metaobjects.loader.MetaDataLoader |
| 7 | +import com.metaobjects.`object`.MetaObject |
| 8 | +import com.metaobjects.relationship.CompositionRelationship |
| 9 | +import com.metaobjects.relationship.MetaRelationship |
| 10 | +import com.metaobjects.source.RdbSource |
| 11 | +import com.squareup.kotlinpoet.TypeName |
| 12 | +import com.squareup.kotlinpoet.LONG |
| 13 | +import java.io.OutputStream |
| 14 | +import java.io.PrintWriter |
| 15 | +import java.nio.file.Files |
| 16 | +import java.nio.file.Path |
| 17 | +import java.nio.file.Paths |
| 18 | +import org.slf4j.LoggerFactory |
| 19 | + |
| 20 | +/** |
| 21 | + * Generator: one `<Entity>Relations.kt` per `object.entity` carrying at least |
| 22 | + * one `relationship.composition @cardinality: many` child. Emits an ergonomic |
| 23 | + * Kotlin extension function per to-many declaration so consumers can write |
| 24 | + * `AuthorTable.postsQuery(author.id).toList()` instead of hand-rolling the |
| 25 | + * `selectAll().where { ... }` JOIN every time. |
| 26 | + * |
| 27 | + * <p>Pairs with {@link KotlinExposedTableGenerator}, which emits the SCHEMA |
| 28 | + * side (the inferred FK column on the many entity's table). This generator |
| 29 | + * owns the QUERY side — the inverse fetch from parent → children — and stays |
| 30 | + * separate from the table emitter so the two concerns don't get tangled. |
| 31 | + * |
| 32 | + * <p>The returned {@link org.jetbrains.exposed.sql.Query} keeps the helper |
| 33 | + * compositional: consumers can chain `.where { ... }`, `.orderBy(...)`, |
| 34 | + * `.limit(...)` etc. before materialising. |
| 35 | + * |
| 36 | + * <p>Convention (matches the inferred FK column emitted by |
| 37 | + * {@link KotlinExposedTableGenerator#buildInverseFkSpec}): |
| 38 | + * <ul> |
| 39 | + * <li>FK column on the target table = {@code <ownerShort.lowercased()>Id} |
| 40 | + * (e.g. {@code Author} → {@code authorId} on {@code PostTable}).</li> |
| 41 | + * <li>Helper fn name = {@code <relShortName>Query} (e.g. {@code postsQuery}).</li> |
| 42 | + * <li>Helper fn parameter = the parent's primary-key field type |
| 43 | + * (resolved via {@code identity.primary.@fields[0]} + KotlinTypeMapper).</li> |
| 44 | + * </ul> |
| 45 | + * |
| 46 | + * <p>Skips silently when: |
| 47 | + * <ul> |
| 48 | + * <li>The entity has no {@code source.rdb} child (no persistence layer).</li> |
| 49 | + * <li>The entity has no to-many composition relationships.</li> |
| 50 | + * <li>The target entity's short name cannot be resolved (defensive).</li> |
| 51 | + * </ul> |
| 52 | + * |
| 53 | + * <p>Args: |
| 54 | + * <ul> |
| 55 | + * <li>{@code outputDir} (required): output directory root.</li> |
| 56 | + * </ul> |
| 57 | + */ |
| 58 | +class KotlinRelationsGenerator : MultiFileDirectGeneratorBase<MetaObject>() { |
| 59 | + |
| 60 | + override fun getFilterClass(): Class<MetaObject> = MetaObject::class.java |
| 61 | + |
| 62 | + override fun execute(loader: MetaDataLoader) { |
| 63 | + parseArgs() |
| 64 | + val outRoot = Paths.get(outDir.absolutePath) |
| 65 | + |
| 66 | + for (entity in loader.metaObjects) { |
| 67 | + if (entity.subType != MetaObject.SUBTYPE_ENTITY) continue |
| 68 | + // No source.rdb → no persistence layer → no FK column to query against. |
| 69 | + entity.children.filterIsInstance<RdbSource>().firstOrNull() ?: continue |
| 70 | + |
| 71 | + val manyRels = entity.children |
| 72 | + .filterIsInstance<MetaRelationship>() |
| 73 | + .filter { |
| 74 | + it.subType == CompositionRelationship.SUBTYPE_COMPOSITION && |
| 75 | + it.cardinality == MetaRelationship.CARDINALITY_MANY |
| 76 | + } |
| 77 | + if (manyRels.isEmpty()) continue |
| 78 | + |
| 79 | + emit(entity, manyRels, outRoot, loader) |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + private fun emit( |
| 84 | + entity: MetaObject, |
| 85 | + manyRels: List<MetaRelationship>, |
| 86 | + outRoot: Path, |
| 87 | + loader: MetaDataLoader, |
| 88 | + ) { |
| 89 | + val (pkg, ownerShort) = PackageMapping.splitFqn(entity.name) |
| 90 | + val ownerTable = ownerShort + "Table" |
| 91 | + val pkParamType = primaryKeyKotlinType(entity) |
| 92 | + val pkParamSimpleName = (pkParamType as? com.squareup.kotlinpoet.ClassName)?.simpleName |
| 93 | + ?: pkParamType.toString().substringAfterLast('.') |
| 94 | + // FK column matches KotlinExposedTableGenerator.buildInverseFkSpec: <ownerShortLowercased>Id. |
| 95 | + val fkColName = ownerShort.replaceFirstChar { it.lowercaseChar() } + "Id" |
| 96 | + |
| 97 | + // Resolve each to-many target → (relShortName, targetShort). Skip relationships |
| 98 | + // whose @objectRef cannot be resolved (defensive — the loader's validation phase |
| 99 | + // already gates the attr being present). |
| 100 | + data class Helper(val relShortName: String, val targetTable: String) |
| 101 | + val helpers = manyRels.mapNotNull { rel -> |
| 102 | + val ref = rel.objectRef ?: return@mapNotNull null |
| 103 | + val target = KotlinGenUtil.resolveObjectByShortOrFqn(loader, ref) ?: return@mapNotNull null |
| 104 | + val targetShort = PackageMapping.splitFqn(target.name).second |
| 105 | + val relShort = rel.shortName ?: rel.name |
| 106 | + Helper(relShort, targetShort + "Table") |
| 107 | + } |
| 108 | + if (helpers.isEmpty()) return |
| 109 | + |
| 110 | + val source = buildString { |
| 111 | + if (pkg.isNotEmpty()) { |
| 112 | + append("package $pkg\n\n") |
| 113 | + } |
| 114 | + append("import org.jetbrains.exposed.sql.Query\n") |
| 115 | + append("import org.jetbrains.exposed.sql.selectAll\n") |
| 116 | + append("\n") |
| 117 | + append("/** GENERATED — extension fns for `$ownerShort` to-many relationships. Do not hand-edit. */\n") |
| 118 | + for ((idx, h) in helpers.withIndex()) { |
| 119 | + if (idx > 0) append("\n") |
| 120 | + append("/** Query `$ownerShort.${h.relShortName}` (cardinality=many) on the ${h.targetTable.removeSuffix("Table")} side. */\n") |
| 121 | + append("fun $ownerTable.${h.relShortName}Query($fkColName: $pkParamSimpleName): Query =\n") |
| 122 | + append(" ${h.targetTable}.selectAll().where { ${h.targetTable}.$fkColName eq $fkColName }\n") |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + val outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(ownerShort + "Relations.kt") |
| 127 | + outFile.parent?.let { Files.createDirectories(it) } |
| 128 | + Files.writeString(outFile, source) |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Resolve the Kotlin type of [entity]'s primary key. Falls back to [LONG] when |
| 133 | + * the primary identity is missing, multi-field, or its field can't be resolved |
| 134 | + * — Long matches the dominant convention (entities almost always have a single |
| 135 | + * `field.long` PK; KotlinExposedTableGenerator's FK columns hard-code |
| 136 | + * `long("…").references(...)`). Same lossy-tolerant policy as the table |
| 137 | + * generator: defensive defaults rather than throwing on partially-formed |
| 138 | + * metadata. |
| 139 | + */ |
| 140 | + private fun primaryKeyKotlinType(entity: MetaObject): TypeName { |
| 141 | + val primary = entity.children |
| 142 | + .filterIsInstance<MetaIdentity>() |
| 143 | + .firstOrNull { it.isPrimary } ?: return LONG |
| 144 | + val pkFieldName = primary.fields.firstOrNull() ?: return LONG |
| 145 | + val pkField = entity.metaFields.firstOrNull { it.name == pkFieldName } ?: return LONG |
| 146 | + return runCatching { KotlinTypeMapper.kotlinTypeName(pkField) }.getOrDefault(LONG) |
| 147 | + } |
| 148 | + |
| 149 | + // === MultiFileDirectGeneratorBase abstract-method stubs ==================== |
| 150 | + override fun writeSingleFile(md: MetaObject, writer: GeneratorIOWriter<*>?) { /* unused */ } |
| 151 | + override fun <T : GeneratorIOWriter<*>?> getSingleWriter( |
| 152 | + loader: MetaDataLoader?, md: MetaObject?, pw: PrintWriter? |
| 153 | + ): T? = null |
| 154 | + override fun <T : GeneratorIOWriter<*>?> getFinalWriter( |
| 155 | + loader: MetaDataLoader?, out: OutputStream? |
| 156 | + ): T? = null |
| 157 | + override fun writeFinalFile(metadata: MutableCollection<MetaObject>?, writer: GeneratorIOWriter<*>?) { /* none */ } |
| 158 | + override fun getSingleOutputFilePath(md: MetaObject): String = |
| 159 | + PackageMapping.splitFqn(md.name).first.replace('.', '/') |
| 160 | + override fun getSingleOutputFilename(md: MetaObject): String = |
| 161 | + PackageMapping.splitFqn(md.name).second + "Relations.kt" |
| 162 | + |
| 163 | + private companion object { |
| 164 | + @JvmStatic |
| 165 | + val LOG = LoggerFactory.getLogger(KotlinRelationsGenerator::class.java) |
| 166 | + } |
| 167 | +} |
0 commit comments