This is an automated email from the ASF dual-hosted git repository. borinquenkid pushed a commit to branch 9.0.x-h7-improvement-phase3 in repository https://gitbox.apache.org/repos/asf/grails-core.git
commit b53eacbe30aa57ac1b06102068358ee64cde6323 Author: Walter Duque de Estrada <[email protected]> AuthorDate: Fri Oct 9 18:24:31 2026 -0500 test(hibernate7): the classic oracle is frozen, and a new fixture is recorded from a native boot The classic binder is gone, so the VERIFY and REFREEZE modes of ClassicOracle, which booted it, go too. The recorded files stay the oracle of the two differential specs (FROZEN, the default: 799 groups, 0 mismatches, 85 known differences, 0 unknown, 0 refused, as before). A contributor who adds an @Entity fixture records it with -Pgrails.test.recordClassicOracle=true: RECORD boots only the scanned groups that have no record, natively, writes their facts at their place in the scan order with the header marked source: native, drops the records of groups no fixture makes up any more, and writes every other record back byte for byte, so the diff to review is additions. The DDL differential compares such a group with its own recorded schema, so a later change of native binding shows up as an unknown difference; the generator differential reports it instead of comparing facets only a classic boot could give (Hibernate's binder fills in a discriminator value, a cache strategy and a length on the version that the classic binder never stated). ClassicOracleSpec proves the three RECORD behaviours on a copy of the file and skips its completeness checks during a recording run, whose classpath still holds the old file. Exercised end to end with a throwaway fixture: 10 lines added, none removed, and the FROZEN rerun green with the record in place. Co-Authored-By: Claude Fable 5.1 <[email protected]> --- gradle/hibernate7-test-config.gradle | 14 +- grails-data-hibernate7/README.md | 35 +++-- .../cfg/domainbinding/jpa/ClassicOracle.groovy | 148 ++++++++++----------- .../cfg/domainbinding/jpa/ClassicOracleSpec.groovy | 121 ++++++++++++----- ...eneratedDomainClassesDdlDifferentialSpec.groovy | 51 +++---- .../GrailsDomainGeneratorDifferentialSpec.groovy | 86 ++++++------ 6 files changed, 251 insertions(+), 204 deletions(-) diff --git a/gradle/hibernate7-test-config.gradle b/gradle/hibernate7-test-config.gradle index c5b100edf8..c2d093d9da 100644 --- a/gradle/hibernate7-test-config.gradle +++ b/gradle/hibernate7-test-config.gradle @@ -46,14 +46,12 @@ tasks.withType(Test).configureEach { useJUnitPlatform() - // The differential specs compare native domain binding against what the classic binder produced, recorded under - // src/test/resources/classic-oracle/. By default they read the recorded files and do not boot the classic binder. - // -Pgrails.test.verifyClassicOracle=true boots it too and asserts it still produces exactly the recorded data; - // -Pgrails.test.refreezeClassicOracle=true boots it and rewrites the files (see ClassicOracle for the details). - ['verifyClassicOracle', 'refreezeClassicOracle'].each { String oracleSwitch -> - if (providers.gradleProperty("grails.test.${oracleSwitch}").map { it.toBoolean() }.getOrElse(false)) { - systemProperty("grails.test.${oracleSwitch}", 'true') - } + // The differential specs compare native domain binding against what the classic binder of Grails 8 produced, recorded + // under src/test/resources/classic-oracle/ before it was deleted. By default they read the recorded files; a scanned + // fixture with no record fails them. -Pgrails.test.recordClassicOracle=true boots such a fixture natively and writes its + // record, leaving the other records as they are (see ClassicOracle for the details). + if (providers.gradleProperty('grails.test.recordClassicOracle').map { it.toBoolean() }.getOrElse(false)) { + systemProperty('grails.test.recordClassicOracle', 'true') } // Lets TCK specs gate features on the running suite. Spock evaluates @IgnoreIf/@Requires // preconditions before setupSpec() runs, so this must be set at the task level - a diff --git a/grails-data-hibernate7/README.md b/grails-data-hibernate7/README.md index dcfea0c232..38565d4999 100644 --- a/grails-data-hibernate7/README.md +++ b/grails-data-hibernate7/README.md @@ -55,34 +55,33 @@ Registered via `META-INF/services/org.grails.cli.compiler.CompilerAutoConfigurat ## Differential specs and the frozen classic oracle (contributors) -Native domain binding (`hibernate.generatedDomainClasses`, `GrailsDomainGenerator`) is checked against what the classic domain binder -(`GrailsDomainBinder`) produces for every `@Entity` in the TCK and in the Hibernate 7 tests, by two specs in +Native domain binding (`GrailsDomainGenerator`, `GeneratedDomainClassBinder`) is the only binding since 9.0.x. It is checked against what +the classic domain binder of Grails 8 produced for every `@Entity` in the TCK and in the Hibernate 7 tests, by two specs in `core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa`: * `GrailsDomainGeneratorDifferentialSpec` compares the facets the generator decides, and what Hibernate's annotation binder reads back from the generated classes, with the facts the classic binder bound (per entity and property); it writes `build/differential-report.txt`. -* `GeneratedDomainClassesDdlDifferentialSpec` boots every group of associated domain classes in the generated mode on H2 and compares the - schema (tables, columns, keys, indexes, checks, sequences, and H2's `SCRIPT NODATA`) with the schema the classic binder derived; it - writes `build/ddl-report.txt`. +* `GeneratedDomainClassesDdlDifferentialSpec` boots every group of associated domain classes on H2 and compares the schema (tables, columns, + keys, indexes, checks, sequences, and H2's `SCRIPT NODATA`) with the schema the classic binder derived; it writes `build/ddl-report.txt`. -The classic side of both comparisons is **recorded data**, not a live classic binder: `core/src/test/resources/classic-oracle/` -(`generator-differential.txt`, `ddl-differential.txt`). `ClassicOracle` documents the format (one record per line, sorted keys, nothing that -varies from run to run) and has three modes: +The classic side of both comparisons is **recorded data**: `core/src/test/resources/classic-oracle/` (`generator-differential.txt`, +`ddl-differential.txt`), written from the classic binder before it was deleted. `ClassicOracle` documents the format (one record per line, +sorted keys, nothing that varies from run to run) and has two modes: | Mode | How | What happens | |---|---|---| -| FROZEN (default) | `./gradlew :grails-data-hibernate7-core:test --tests '*DifferentialSpec'` | The classic binder is not booted. The recorded files are the oracle. A scanned fixture with no recorded group fails with a message that says to refreeze. | -| VERIFY | add `-Pgrails.test.verifyClassicOracle=true` | The classic binder is booted too and what it produces must equal the recorded files exactly (the freeze is faithful and current); the comparison then runs as in FROZEN. | -| REFREEZE | add `-Pgrails.test.refreezeClassicOracle=true` | The classic binder is booted and the files are rewritten. Review and commit the diff: a changed record is a change in what the classic binder does, or a new or changed fixture. | - -Run VERIFY after changing a fixture, classic binder code or Hibernate, and REFREEZE only to record that change. The `KNOWN` +| FROZEN (default) | `./gradlew :grails-data-hibernate7-core:test --tests '*DifferentialSpec'` | The recorded files are the oracle. A scanned fixture with no recorded group, or whose group changed, fails with a message that says to record it; a recorded group no fixture makes up any more is reported. | +| RECORD | add `-Pgrails.test.recordClassicOracle=true` | A scanned group that has no record is booted natively and its facts are written to the files, at its place in the scan order; the records of groups no fixture makes up any more are dropped; every other record is written back as it is. Review and commit the diff. | + +Every `@Entity` under `core/src/test` is scanned, so **a new domain class in a spec needs a record**: run the two differential specs once +in RECORD mode and check that the diff of the two files is additions only (plus the lines of a fixture you deleted). The new records state +what native binding does, since no classic binder is left to ask (the section is marked `source: native`: the DDL differential compares its +schema, so a later change of native binding shows up as an unknown difference; the generator differential reports it instead of comparing +facets only a classic boot could give). Prefer an existing fixture when a spec can use one. The `KNOWN` list of the DDL spec states why each remaining difference between native and classic binding is kept; it is not part of the recording. `ClassicOracleSpec` and the "changed recorded fact" features of the two differential specs prove that the serialisation is stable, that -the files cover every scanned fixture, and that changing a recorded fact makes the comparison fail. - -The classic binder is internal code that is being retired. When it is deleted, the VERIFY and REFREEZE modes go with it, the recorded files -become plain expectations, and a new fixture gets its records written by hand (copy the records of a similar fixture into the group of the -new one, in the format `ClassicOracle` reads). +the files cover every scanned fixture, that changing a recorded fact makes the comparison fail, and that RECORD touches only the records of +new and gone groups. ## Using GORM Without Grails diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy index aea8ea2a97..a0e77b22f9 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracle.groovy @@ -22,35 +22,40 @@ import groovy.json.JsonOutput import groovy.json.JsonSlurper /** - * The frozen oracle of the differential specs: what the classic domain binder produced for the scanned test domains, recorded once - * as text under {@code src/test/resources/classic-oracle/} so that the specs compare the native binding against recorded data - * instead of against a live classic binder. + * The frozen oracle of the differential specs: what the classic domain binder of Grails 8 produced for the scanned test domains, + * recorded once, before it was deleted, as text under {@code src/test/resources/classic-oracle/}. The specs compare native binding + * against these recorded facts. * - * <p>There are three modes, chosen with Gradle properties (wired to system properties in {@code gradle/hibernate7-test-config.gradle}):</p> + * <p>There are two modes, chosen with a Gradle property (wired to a system property in {@code gradle/hibernate7-test-config.gradle}):</p> * <ul> - * <li><b>FROZEN</b> (the default): the classic binder is not booted; the recorded files are the oracle.</li> - * <li><b>VERIFY</b> ({@code -Pgrails.test.verifyClassicOracle=true}): the classic binder is booted live, what it produces is - * serialised the way the files are and must EQUAL the recorded files (the freeze is faithful and current); the comparison then runs - * as in FROZEN mode.</li> - * <li><b>REFREEZE</b> ({@code -Pgrails.test.refreezeClassicOracle=true}): the classic binder is booted live and the files are rewritten.</li> + * <li><b>FROZEN</b> (the default): the recorded files are the oracle. A scanned group with no record, or whose classes changed, + * fails with a message that says how to record it; a recorded group no fixture makes up any more is reported as drift.</li> + * <li><b>RECORD</b> ({@code -Pgrails.test.recordClassicOracle=true}): the way a contributor adds a fixture. A scanned group that + * has no record (or whose classes changed) is booted natively, by the closure the spec passes, and its facts are written to the + * file at its place in the scan order; the records of every other group are written back as they are, and the records of groups + * no fixture makes up any more are dropped. The diff is what the contributor reviews: for a new fixture it is only additions, and + * they state what native binding does, since no classic binder is left to ask. Such a section carries {@code source: native} in + * its header: the DDL differential compares its schema (a later change of native binding shows up), the generator differential + * does not compare its facets, which only a classic boot could give, and reports it.</li> * </ul> * - * <p>Once the classic binder is deleted VERIFY and REFREEZE go with it; a new fixture then gets its recorded entries by hand.</p> - * * <p>The files are plain text, one record per line, sorted and without anything that varies from run to run. A line is * {@code kind TAB key TAB json}; a line {@code @group TAB key TAB json} opens the section of one group of domain classes, whose - * header lists the member classes (so a changed fixture set is detected) and, for a group the classic binder cannot boot, the - * first line of the reason.</p> + * header lists the member classes (so a changed fixture set is detected) and, for a group that cannot boot, the first line of + * the reason.</p> */ class ClassicOracle { - static final String VERIFY_PROPERTY = 'grails.test.verifyClassicOracle' - static final String REFREEZE_PROPERTY = 'grails.test.refreezeClassicOracle' + static final String RECORD_PROPERTY = 'grails.test.recordClassicOracle' + /** The header value that marks a section recorded from a native boot. */ + static final String NATIVE_SOURCE = 'native' static final String RESOURCE_DIRECTORY = 'classic-oracle' - static final String REFREEZE_HINT = 'run the spec with -Pgrails.test.refreezeClassicOracle=true (it boots the classic binder and rewrites ' + - 'src/test/resources/classic-oracle/) and commit the changed files' + static final File DEFAULT_DIRECTORY = new File("src/test/resources/${RESOURCE_DIRECTORY}") + static final String RECORD_HINT = 'run the differential specs with -Pgrails.test.recordClassicOracle=true: a scanned group that has ' + + 'no record is booted natively and its facts are written to src/test/resources/classic-oracle/, the records of groups no ' + + 'fixture makes up any more are dropped, and every other record is written back as it is; review the diff and commit it' - enum Mode { FROZEN, VERIFY, REFREEZE } + enum Mode { FROZEN, RECORD } /** One group of domain classes: its header and its records. */ static class Section { @@ -88,28 +93,30 @@ class ClassicOracle { final String name final Mode mode + private final File directory private final Map<String, Section> recorded = new LinkedHashMap<String, Section>() private final Map<String, Section> fresh = new LinkedHashMap<String, Section>() - private final Set<String> visited = new LinkedHashSet<String>() + private final List<String> visited = [] + /** FROZEN: the recorded groups no scanned fixture makes up any more. */ final List<String> drift = [] + /** RECORD: the groups recorded by this run. */ + final List<String> recordedNow = [] + /** RECORD: the recorded groups dropped from the file because no scanned fixture makes them up any more. */ + final List<String> dropped = [] ClassicOracle(String name) { this(name, currentMode()) } - ClassicOracle(String name, Mode mode) { + ClassicOracle(String name, Mode mode, File directory = DEFAULT_DIRECTORY) { this.name = name this.mode = mode - if (mode != Mode.REFREEZE) { - recorded.putAll(read(name)) - } + this.directory = directory + recorded.putAll(read(name)) } static Mode currentMode() { - if (Boolean.getBoolean(REFREEZE_PROPERTY)) { - return Mode.REFREEZE - } - return Boolean.getBoolean(VERIFY_PROPERTY) ? Mode.VERIFY : Mode.FROZEN + return Boolean.getBoolean(RECORD_PROPERTY) ? Mode.RECORD : Mode.FROZEN } /** The recorded section of the group whose first member is the key, or null: for the specs of the oracle itself. */ @@ -121,53 +128,59 @@ class ClassicOracle { return recorded.keySet() } - /** True when the classic binder has to be booted (VERIFY and REFREEZE). */ - boolean isLive() { - return mode != Mode.FROZEN - } - /** - * The recorded section of a group. In FROZEN mode the closure is not called; in VERIFY mode it is called and its section must equal - * the recorded one; in REFREEZE mode it is called and its section becomes the record. + * The section of a group: the recorded one when the group is recorded with these classes. Otherwise the group is new or + * changed: FROZEN fails and says how to record it, RECORD calls the closure and keeps its section for the file. * * @param key the first member of the group (groups never share a class) * @param members the names of the classes of the group - * @param classic boots the classic binder and builds the section + * @param record boots the group natively and builds its section */ - Section section(String key, List<String> members, Closure<Section> classic) { + Section section(String key, List<String> members, Closure<Section> record) { visited << key - if (mode == Mode.REFREEZE) { - Section section = classic.call() - fresh[key] = section - return section - } Section stored = recorded[key] - if (stored == null || stored.header.members != members) { + if (stored != null && stored.header.members == members) { + return stored + } + if (mode == Mode.FROZEN) { throw new IllegalStateException( "The classic oracle '${name}' has no recorded data for the group of ${key} with the classes ${members} " + - "(a new or changed fixture): ${REFREEZE_HINT}".toString()) + "(a new or changed fixture): ${RECORD_HINT}".toString()) } - if (mode == Mode.VERIFY) { - Section live = classic.call() - fresh[key] = live - if (live.render() != stored.render()) { - drift << "${key}: ${firstDifference(stored.render(), live.render())}".toString() - } - } - return stored + Section section = record.call() + fresh[key] = section + recordedNow << key + return section } - /** Ends a run: rewrites the files (REFREEZE), and reports recorded groups no fixture backs any more. */ + /** + * Ends a run. FROZEN reports the recorded groups no fixture backs any more. RECORD writes the file when a group was recorded + * or a recorded group is gone: the recorded sections in their order, a recorded group inserted after the scanned group that + * precedes it, the groups no fixture makes up any more left out. + */ void finish() { - if (mode == Mode.REFREEZE) { - File file = new File("src/test/resources/${RESOURCE_DIRECTORY}/${name}.txt") - file.parentFile.mkdirs() - file.setText(render(fresh), 'UTF-8') + List<String> stale = recorded.keySet().findAll { String key -> !visited.contains(key) }.toList() + if (mode == Mode.FROZEN) { + stale.each { String key -> + drift << "${key}: recorded in '${name}' but no scanned fixture makes up this group any more: ${RECORD_HINT}".toString() + } return } - recorded.keySet().findAll { String key -> !visited.contains(key) }.each { String key -> - drift << "${key}: recorded in '${name}' but no scanned fixture makes up this group any more".toString() + dropped.addAll(stale) + if (fresh.isEmpty() && stale.isEmpty()) { + return } + List<String> order = recorded.keySet().findAll { String key -> visited.contains(key) }.toList() + for (String key : recordedNow) { + int at = visited.indexOf(key) + String before = at == 0 ? null : (at - 1..0).collect { int i -> visited[i] }.find { String candidate -> order.contains(candidate) } + order.add(before == null ? 0 : order.indexOf(before) + 1, key) + } + Map<String, Section> sections = new LinkedHashMap<String, Section>() + order.each { String key -> sections[key] = fresh[key] ?: recorded[key] } + File file = new File(directory, "${name}.txt") + file.parentFile.mkdirs() + file.setText(render(sections), 'UTF-8') } static String render(Map<String, Section> sections) { @@ -180,7 +193,7 @@ class ClassicOracle { String path = "/${RESOURCE_DIRECTORY}/${name}.txt" InputStream stream = ClassicOracle.getResourceAsStream(path) if (stream == null) { - throw new IllegalStateException("The classic oracle file ${path} is missing: ${REFREEZE_HINT}".toString()) + throw new IllegalStateException("The classic oracle file ${path} is missing: ${RECORD_HINT}".toString()) } return stream.withCloseable { InputStream input -> parseText(input.getText('UTF-8')) } } @@ -203,19 +216,6 @@ class ClassicOracle { return sections } - private static String firstDifference(String recorded, String live) { - List<String> a = recorded.readLines() - List<String> b = live.readLines() - for (int i = 0; i < Math.max(a.size(), b.size()); i++) { - String left = i < a.size() ? a[i] : '<missing>' - String right = i < b.size() ? b[i] : '<missing>' - if (left != right) { - return "line ${i + 1} differs: recorded=${left.take(300)} live=${right.take(300)}".toString() - } - } - return 'no difference' - } - /** * The deterministic serialisation: map keys sorted, lists in order, no spaces; a map entry whose value is null is left out unless * {@code keepNulls} (a recorded fact that is absent reads as null). @@ -223,8 +223,8 @@ class ClassicOracle { static String canonical(Object value, boolean keepNulls = false) { StringBuilder out = new StringBuilder() write(out, value, keepNulls) - // the domain binder names an index after the closure mapped as the index of a collection (...$_closure2@3ff5aef4), which holds - // the identity of the closure instance and differs on every boot + // an index named after the closure mapped as the index of a collection (...$_closure2@3ff5aef4) holds the identity of the + // closure instance, which differs on every boot return out.toString().replaceAll(/(_closure\d+)@[0-9a-f]+/, '$1@0') } diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy index d6bd6a95e2..648f5ac63d 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/ClassicOracleSpec.groovy @@ -18,6 +18,7 @@ */ package org.grails.orm.hibernate.cfg.domainbinding.jpa +import spock.lang.IgnoreIf import spock.lang.Shared import spock.lang.Specification import spock.lang.Unroll @@ -25,9 +26,9 @@ import spock.lang.Unroll /** * The frozen oracle itself ({@link ClassicOracle}): that its serialisation is deterministic, that the recorded files are the canonical * rendering of what they hold and cover every scanned fixture, that a fixture without recorded data is refused with a message that says how - * to record it, and that the VERIFY mode notices a recorded group the classic binder no longer produces. That a changed recorded fact makes - * the comparison fail is proven in {@code GrailsDomainGeneratorDifferentialSpec} and {@code GeneratedDomainClassesDdlDifferentialSpec}, - * which own the comparisons. + * to record it, and that the RECORD mode records exactly the groups that have no record and writes every other record back as it is. That + * a changed recorded fact makes the comparison fail is proven in {@code GrailsDomainGeneratorDifferentialSpec} and + * {@code GeneratedDomainClassesDdlDifferentialSpec}, which own the comparisons. */ class ClassicOracleSpec extends Specification { @@ -100,6 +101,8 @@ class ClassicOracleSpec extends Specification { oracle << ORACLES } + @IgnoreIf(value = { ClassicOracle.currentMode() == ClassicOracle.Mode.RECORD }, + reason = 'a recording run writes the file the differential specs read from the classpath; run again to check it') @Unroll void "the recorded file #oracle holds every scanned group, and only those"() { given: @@ -128,6 +131,8 @@ class ClassicOracleSpec extends Specification { oracle << ORACLES } + @IgnoreIf(value = { ClassicOracle.currentMode() == ClassicOracle.Mode.RECORD }, + reason = 'a recording run writes the file the differential specs read from the classpath; run again to check it') void "the groups the classic binder booted have their entities in the generator oracle and their tables and statements in the DDL oracle"() { given: ClassicOracle generator = new ClassicOracle('generator-differential', ClassicOracle.Mode.FROZEN) @@ -156,7 +161,7 @@ class ClassicOracleSpec extends Specification { then: IllegalStateException e = thrown() e.message.contains('org.example.NewFixture') - e.message.contains('-Pgrails.test.refreezeClassicOracle=true') + e.message.contains('-Pgrails.test.recordClassicOracle=true') e.message.contains('src/test/resources/classic-oracle/') !booted @@ -176,13 +181,13 @@ class ClassicOracleSpec extends Specification { then: IllegalStateException e = thrown() - e.message.contains('-Pgrails.test.refreezeClassicOracle=true') + e.message.contains('-Pgrails.test.recordClassicOracle=true') where: oracle << ORACLES } - void "the frozen mode does not call the classic binder for a recorded group and returns the recorded section"() { + void "the frozen mode does not call the recorder for a recorded group and returns the recorded section"() { given: ClassicOracle frozen = new ClassicOracle('ddl-differential', ClassicOracle.Mode.FROZEN) String key = frozen.recordedKeys().first() @@ -194,49 +199,101 @@ class ClassicOracleSpec extends Specification { then: !booted - !frozen.isLive() section.is(frozen.recordedSection(key)) frozen.drift.isEmpty() } - void "the verify mode notices a group the classic binder no longer produces as it was recorded"() { + void "the frozen mode reports recorded groups that were not visited, with the way to drop them"() { given: - ClassicOracle verify = new ClassicOracle('ddl-differential', ClassicOracle.Mode.VERIFY) - ClassicOracle.Section recorded = verify.recordedSection(verify.recordedKeys().find { - verify.recordedSection(it).header.unbootable == null - }) - List<String> members = (List<String>) recorded.header.members - ClassicOracle.Section same = new ClassicOracle.Section(recorded.key, recorded.header) - same.records.addAll(recorded.records) - ClassicOracle.Section other = new ClassicOracle.Section(recorded.key, recorded.header) - other.records.addAll(recorded.records) - other.records[0] = [other.records[0][0], other.records[0][1], '{"changed":true}'] + ClassicOracle frozen = new ClassicOracle('generator-differential', ClassicOracle.Mode.FROZEN) when: - verify.section(recorded.key, members) { same } + frozen.finish() - then: "the same section is the recorded one" - verify.isLive() - verify.drift.isEmpty() + then: + frozen.drift.size() == frozen.recordedKeys().size() + frozen.drift.every { String line -> line.contains('no scanned fixture') && line.contains('-Pgrails.test.recordClassicOracle=true') } + } + + void "the record mode returns a recorded group without calling the recorder, and writes nothing when every record is backed"() { + given: + File directory = File.createTempDir('classic-oracle', 'record') + ClassicOracle record = new ClassicOracle('ddl-differential', ClassicOracle.Mode.RECORD, directory) + boolean booted = false when: - verify.section(recorded.key, members) { other } + record.recordedKeys().each { String key -> + record.section(key, (List<String>) record.recordedSection(key).header.members) { booted = true; null } + } + record.finish() - then: "a section that differs is reported with the first line that does" - verify.drift.size() == 1 - verify.drift[0].contains(recorded.key) - verify.drift[0].contains('differs') + then: + !booted + record.recordedNow.isEmpty() + record.dropped.isEmpty() + !new File(directory, 'ddl-differential.txt').exists() + + cleanup: + directory.deleteDir() } - void "the verify mode reports recorded groups that were not visited"() { + void "the record mode records a group that has no record from the recorder, at its place in the scan order, and writes every other record back as it is"() { given: - ClassicOracle verify = new ClassicOracle('generator-differential', ClassicOracle.Mode.VERIFY) + File directory = File.createTempDir('classic-oracle', 'record') + String original = ClassicOracle.getResourceAsStream("/${ClassicOracle.RESOURCE_DIRECTORY}/ddl-differential.txt").getText('UTF-8') + ClassicOracle record = new ClassicOracle('ddl-differential', ClassicOracle.Mode.RECORD, directory) + List<String> keys = record.recordedKeys().toList() + ClassicOracle.Section fresh = new ClassicOracle.Section('org.example.NewFixture', [members: ['org.example.NewFixture']]) + fresh.add('table', 'new_fixture', [columns: [id: [type: 'bigint']]], true) + int booted = 0 + + when: "the scan visits the new group after the third recorded one" + keys.eachWithIndex { String key, int index -> + record.section(key, (List<String>) record.recordedSection(key).header.members) { booted++; null } + if (index == 2) { + record.section('org.example.NewFixture', ['org.example.NewFixture']) { booted++; fresh } + } + } + record.finish() + String written = new File(directory, 'ddl-differential.txt').getText('UTF-8') + + then: "the recorder ran for the new group only" + booted == 1 + record.recordedNow == ['org.example.NewFixture'] + record.dropped.isEmpty() + + and: "the file is the original with the new section inserted after the third group, byte for byte otherwise" + written.length() == original.length() + fresh.render().length() + written.startsWith(original.substring(0, original.indexOf("@group\t${keys[3]}\t"))) + written.endsWith(original.substring(original.indexOf("@group\t${keys[3]}\t"))) + written.contains(fresh.render()) + ClassicOracle.parseText(written).keySet().toList() == keys[0..2] + ['org.example.NewFixture'] + keys[3..-1] + + cleanup: + directory.deleteDir() + } + + void "the record mode drops a recorded group no scanned fixture makes up any more and says so"() { + given: + File directory = File.createTempDir('classic-oracle', 'record') + ClassicOracle record = new ClassicOracle('ddl-differential', ClassicOracle.Mode.RECORD, directory) + List<String> keys = record.recordedKeys().toList() + String gone = keys.last() when: - verify.finish() + keys.findAll { it != gone }.each { String key -> + record.section(key, (List<String>) record.recordedSection(key).header.members) { null } + } + record.finish() + Map<String, ClassicOracle.Section> written = ClassicOracle.parseText(new File(directory, 'ddl-differential.txt').getText('UTF-8')) then: - verify.drift.size() == verify.recordedKeys().size() - verify.drift.every { String line -> line.contains('no scanned fixture') } + record.dropped == [gone] + record.recordedNow.isEmpty() + written.keySet().toList() == keys - gone + written.values()*.render() == (keys - gone).collect { String key -> record.recordedSection(key).render() } + + cleanup: + directory.deleteDir() } } diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy index 5bb9d68b8b..67e5f75a42 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GeneratedDomainClassesDdlDifferentialSpec.groovy @@ -45,18 +45,16 @@ import org.grails.datastore.mapping.reflect.ClassUtils import org.grails.orm.hibernate.HibernateDatastore /** - * What a user with an existing database would see if they switched {@code hibernate.generatedDomainClasses} on: the schema - * Hibernate derives from the generated classes against the schema the domain binder derives from the same domain classes. - * - * <p>Every group of associated domain classes of the scanned test domains ({@link ScannedDomainClasses}) is booted twice - * on H2, once in each mode, and the Hibernate mapping model of both (tables, columns with their type, nullability, default, - * length, precision and scale, primary keys with their column order, foreign keys, unique keys, indexes, check constraints, - * sequences) is compared. As a backstop for what the model does not show, the schema H2 itself holds after the boot - * ({@code SCRIPT NODATA}, with H2's generated constraint names normalised) is compared too, and a statement that differs - * for a table with no difference in the model fails the spec as an unexplained difference.</p> + * Compares the schema native binding derives from every group of related domain classes of the test suites with the schema the + * classic domain binder of Grails 8 derived from them, recorded in {@code classic-oracle/ddl-differential.txt} before it was + * deleted ({@link ClassicOracle}): tables, columns with their types, nullability, defaults and lengths, primary keys and their + * column order, foreign keys, unique keys, indexes, check constraints and sequences, and H2's {@code SCRIPT NODATA} (with the + * generated constraint names normalised). What a user with an existing database created by Grails 8 sees when the upgraded + * application starts against it. * * <p>The spec fails on every difference that is not covered by an entry of {@link #KNOWN}, each of which states why the - * difference is kept. The categorised report is written to {@code build/ddl-report.txt}.</p> + * difference is kept, and on an H2 statement that differs without a known difference explaining it. A new fixture gets its record + * from a native boot with {@code -Pgrails.test.recordClassicOracle=true} ({@link #nativeSection}).</p> */ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { @@ -143,7 +141,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { int scriptStatements = 0 for (List<Class<?>> group : groups) { String name = group*.simpleName.join(',').take(120) - ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { classicSection(group) } + ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { nativeSection(group) } if (section.header.unbootable != null) { binderUnbootable[name] = section.header.unbootable.toString() continue @@ -154,7 +152,7 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { } Map generated try { - generated = (Map) ClassicOracle.normalized(snapshot(group, true), true) + generated = (Map) ClassicOracle.normalized(snapshot(group), true) } catch (Throwable e) { generatedRefused[name] = firstLine(e) continue @@ -173,17 +171,19 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { } /** - * What the domain binder produces for a group, as a section of the oracle file: the snapshot of the schema it derived, or the first - * line of the reason it cannot boot the group. Only called when the classic binder is booted (VERIFY and REFREEZE). + * The record of a group that has none, taken from a native boot (the files were recorded from the classic binder before it was + * deleted; this is how a new fixture joins them): the snapshot of the schema, or the first line of the reason the group cannot + * boot. Only called in the RECORD mode of {@link ClassicOracle}. */ - static ClassicOracle.Section classicSection(List<Class<?>> group) { + static ClassicOracle.Section nativeSection(List<Class<?>> group) { Map schema try { - schema = snapshot(group, false) + schema = snapshot(group) } catch (Throwable e) { - return new ClassicOracle.Section(group.first().name, [members: group*.name, unbootable: ClassicOracle.stableReason(firstLine(e))]) + return new ClassicOracle.Section(group.first().name, + [members: group*.name, source: ClassicOracle.NATIVE_SOURCE, unbootable: ClassicOracle.stableReason(firstLine(e))]) } - ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name]) + ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name, source: ClassicOracle.NATIVE_SOURCE]) ((Map<String, Map>) schema.tables).keySet().sort().each { String table -> section.add('table', table, schema.tables[table], true) } ((Map<String, Map>) schema.sequences).keySet().sort().each { String sequence -> section.add('sequence', sequence, schema.sequences[sequence], true) } ((List<String>) schema.script).each { String statement -> section.add('script', '', statement, true) } @@ -272,14 +272,12 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { } /** - * Boots a group in one mode, with the settings of the other mode identical, and reads the schema model and the H2 script - * back as plain data so that the datastore can be closed. + * Boots a group and reads the schema model and the H2 script back as plain data so that the datastore can be closed. */ - private static Map snapshot(List<Class<?>> group, boolean generated) { + private static Map snapshot(List<Class<?>> group) { Map<String, Object> config = [ - 'dataSource.url' : "jdbc:h2:mem:ddlDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), - 'dataSource.dbCreate' : 'create-drop', - 'hibernate.generatedDomainClasses': generated, + 'dataSource.url' : "jdbc:h2:mem:ddlDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate': 'create-drop', ] if (group.any { Class<?> type -> ClassUtils.isMultiTenant(type) }) { config['grails.gorm.multiTenancy.mode'] = MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR @@ -572,8 +570,11 @@ class GeneratedDomainClassesDdlDifferentialSpec extends Specification { "with the domain binder, ${generatedRefused.size()} refused by the generated mode; ${tables} tables, " + "${scriptStatements} H2 statements; ${differences.size()} differences, ${unknown.size()} not known, " + "${unexplained.size()} unexplained H2 statements\n" - report << "classic oracle: ${oracle.mode}${oracle.drift.isEmpty() ? '' : ", ${oracle.drift.size()} recorded groups differ from the live classic binder"}\n" + report << "classic oracle: ${oracle.mode}${oracle.recordedNow.isEmpty() ? '' : ", ${oracle.recordedNow.size()} groups recorded from a native boot"}" + + "${oracle.dropped.isEmpty() ? '' : ", ${oracle.dropped.size()} recorded groups dropped"}\n" oracle.drift.each { report << " DRIFT ${it}\n" } + oracle.recordedNow.each { report << " RECORDED ${it}\n" } + oracle.dropped.each { report << " DROPPED ${it}\n" } report << '\n' report << "difference classes (kind, on a join table or not): count, example\n" Map<String, List<Map>> byClass = differences.groupBy { Map d -> d.cls } diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy index 370a2a29ba..2bcd3bd7c2 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/jpa/GrailsDomainGeneratorDifferentialSpec.groovy @@ -64,16 +64,16 @@ import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndP import org.grails.orm.hibernate.cfg.domainbinding.util.DefaultColumnNameFetcher /** - * Compares {@link GrailsDomainGenerator} with the domain binder on real entities. For every supported property of - * every entity the binder can bind, the column facets the generator decides must equal the ones the binder put on the - * bound Hibernate {@code Column} and {@code Property}. The binder is the oracle, so a mismatch is either a generator - * bug or a rule that was mirrored wrongly. + * Compares {@link GrailsDomainGenerator} with the classic domain binder of Grails 8 on real entities. For every supported + * property of every entity the classic binder could bind, the column facets the generator decides must equal the ones the + * classic binder put on the bound Hibernate {@code Column} and {@code Property}. The classic binder is the oracle, so a mismatch + * is either a generator bug or a rule that was mirrored wrongly. * - * <p>The oracle is FROZEN: what the binder bound is read from {@code classic-oracle/generator-differential.txt} - * ({@link ClassicOracle}, {@link ClassicFacts}), recorded once, and the classic binder is not booted. The generator's side is read - * from the mapping of a datastore booted through the generated classes. {@code -Pgrails.test.verifyClassicOracle=true} boots the - * classic binder too and requires it to produce exactly the recorded facts; {@code -Pgrails.test.refreezeClassicOracle=true} - * rewrites the file from it.</p> + * <p>The oracle is FROZEN: what the classic binder bound is read from {@code classic-oracle/generator-differential.txt} + * ({@link ClassicOracle}, {@link ClassicFacts}), recorded once before the classic binder was deleted. The generator's side is read + * from the mapping of a datastore booted through the generated classes. A new fixture gets its record from a native boot with + * {@code -Pgrails.test.recordClassicOracle=true} ({@link #nativeSection}); its comparison is then native against native, and the + * diff of the recorded file is what is reviewed.</p> * * <p>The entities are every domain class in the TCK and in the Hibernate 7 tests, which are written to exercise * binder permutations. They are grouped by association so each group boots as its own datastore; a group that cannot @@ -157,6 +157,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { List<String> oracleProblems = [] Map<String, Integer> skipped = [:].withDefault { 0 } Map<String, String> unbootable = [:] + Map<String, Integer> nativeRecorded = [:] int compared = 0 int entities = 0 int derived = 0 @@ -177,11 +178,18 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { List<String> rejectedComposites = [] for (List<Class<?>> group : groups) { - ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { classicSection(group) } + ClassicOracle.Section section = oracle.section(group.first().name, group*.name) { nativeSection(group) } if (section.header.unbootable != null) { unbootable[group*.simpleName.join(',')] = section.header.unbootable.toString() continue } + if (section.header.source == ClassicOracle.NATIVE_SOURCE) { + // recorded from a native boot after the classic binder was deleted: the bound facts hold what Hibernate's own binder + // fills in (the default discriminator value, the default cache strategy, a length on the version), which no classic + // binding ever stated, so there are no classic facets to compare; the DDL differential compares the schema + nativeRecorded[group*.simpleName.join(',')] = section.parsedByKey('entity').size() + continue + } classic = section.parsedByKey('entity') classicFilters = section.parsedByKey('filter') if (perturb != null) { @@ -198,7 +206,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { List<GrailsHibernatePersistentEntity> boundEntities = datastore.mappingContext.getHibernatePersistentEntities() .findAll { group.contains(it.javaClass) && classic.containsKey(it.name) } if (boundEntities*.name.toSet() != classic.keySet()) { - oracleProblems << "${group*.simpleName.join(',')}: the recorded entities ${classic.keySet()} are not the entities ${boundEntities*.name} the mapping holds: ${ClassicOracle.REFREEZE_HINT}".toString() + oracleProblems << "${group*.simpleName.join(',')}: the recorded entities ${classic.keySet()} are not the entities ${boundEntities*.name} the mapping holds: ${ClassicOracle.RECORD_HINT}".toString() } boundEntities.each { GrailsHibernatePersistentEntity entity -> replayJoinTables(entity) } for (GrailsHibernatePersistentEntity entity : boundEntities) { @@ -354,7 +362,7 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } } return [ - mismatches: mismatches, oracleProblems: oracleProblems, skipped: skipped, unbootable: unbootable, compared: compared, + mismatches: mismatches, oracleProblems: oracleProblems, skipped: skipped, unbootable: unbootable, nativeRecorded: nativeRecorded, compared: compared, entities: entities, derived: derived, embeddedProperties: embeddedProperties, embeddedLeaves: embeddedLeaves, explicitTypes: explicitTypes, collections: collections, known: known, tenants: tenants, strategies: strategies, hierarchies: hierarchies, annotationRead: annotationRead, associations: associations, constraints: constraints, @@ -369,8 +377,11 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { report << "differential: ${candidates} candidate classes in ${groups} groups; " + "${unbootable.size()} groups could not boot alone; ${result.entities} entities, ${result.compared} properties compared " + "(${result.derived} derived); ${result.embeddedProperties} embedded properties compared, ${result.embeddedLeaves} embedded columns\n" - report << "classic oracle: ${oracle.mode}${oracle.drift.isEmpty() ? '' : ", ${oracle.drift.size()} recorded groups differ from the live classic binder"}\n" + report << "classic oracle: ${oracle.mode}${oracle.recordedNow.isEmpty() ? '' : ", ${oracle.recordedNow.size()} groups recorded from a native boot"}" + + "${oracle.dropped.isEmpty() ? '' : ", ${oracle.dropped.size()} recorded groups dropped"}\n" oracle.drift.each { report << "DRIFT ${it}\n" } + oracle.recordedNow.each { report << "RECORDED ${it}\n" } + oracle.dropped.each { report << "DROPPED ${it}\n" } result.oracleProblems.each { report << "ORACLE ${it}\n" } report << "explicit types compared: ${result.explicitTypes}\n" report << "collections of basic values compared by kind: ${result.collections}\n" @@ -388,28 +399,31 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { report << "unsupported by kind: ${result.skipped}\n" report << "mismatches by facet: ${mismatches.groupBy { (it =~ /\s(\w+): generator=/)[0][1] }.collectEntries { k, v -> [k, v.size()] }}\n" unbootable.each { report << "unbootable: ${it.key.take(120)} -> ${it.value.take(200)}\n" } + ((Map<String, Integer>) result.nativeRecorded).each { report << "recorded from a native boot, not compared: ${it.key.take(120)} (${it.value} entities)\n" } mismatches.each { report << "MISMATCH ${it}\n" } new File('build/differential-report.txt').text = report.toString() } /** - * What the classic binder bound for a group, as a section of the oracle file: for each entity the facts {@link ClassicFacts} reads - * from its {@code PersistentClass} (and the identifier generator the session factory holds for a root with a simple identifier), the - * filter definitions of the session factory, or the first line of the reason it cannot boot the group. Only called when the classic - * binder is booted (VERIFY and REFREEZE). + * The record of a group that has none, taken from a native boot (the files were recorded from the classic binder before it was + * deleted; this is how a new fixture joins them): for each entity the facts {@link ClassicFacts} reads from its bound + * {@code PersistentClass} (and the identifier generator the session factory holds for a root with a simple identifier), the join + * table state of its collection properties, the filter definitions of the session factory, or the first line of the reason the + * group cannot boot. Only called in the RECORD mode of {@link ClassicOracle}. */ - static ClassicOracle.Section classicSection(List<Class<?>> group) { + static ClassicOracle.Section nativeSection(List<Class<?>> group) { HibernateDatastore datastore try { - datastore = boot(group) + datastore = bootGenerated(group) } catch (Throwable e) { return new ClassicOracle.Section(group.first().name, [ members : group*.name, + source : ClassicOracle.NATIVE_SOURCE, unbootable: ClassicOracle.stableReason((e.message ?: e.getClass().simpleName).readLines().first()), ]) } try { - ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name]) + ClassicOracle.Section section = new ClassicOracle.Section(group.first().name, [members: group*.name, source: ClassicOracle.NATIVE_SOURCE]) SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) datastore.sessionFactory List<GrailsHibernatePersistentEntity> bound = datastore.mappingContext.getHibernatePersistentEntities() .findAll { group.contains(it.javaClass) && it.persistentClass != null && it.persistentClass.entityName == it.name } @@ -447,9 +461,9 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } /** - * Puts back on the mapping of an entity the join tables the classic binder left on it. The classic binder writes into the mapping while it - * binds (the inverse side of a many-to-many adopts the owning side's join table, a circular many-to-many gets a renamed key) and this - * comparison has always read the mapping the binder left, so the generator reads the same state here, on a mapping the binder never touched. + * Puts back on the mapping of an entity the join table state recorded for it. The classic binder wrote into the mapping while it + * bound (the inverse side of a many-to-many adopted the owning side's join table, a circular many-to-many got a renamed key) and + * this comparison has always read the mapping it left, so the generator reads the same state here, on a mapping nothing wrote into. */ private void replayJoinTables(GrailsHibernatePersistentEntity entity) { Map<String, Map> states = (Map<String, Map>) classic[entity.name].joinTables ?: [:] @@ -459,36 +473,14 @@ class GrailsDomainGeneratorDifferentialSpec extends HibernateGormDatastoreSpec { } } - /** - * Boots a group of entities with the classic binder (stated, since native binding is the default). GORM only gives an entity a tenant id (and the binder only adds the tenant filter) in - * discriminator multi-tenancy mode, so a group with multi-tenant entities is booted in that mode when it can be. - */ - private static HibernateDatastore boot(List<Class<?>> group) { - if (group.any { Class<?> type -> ClassUtils.isMultiTenant(type) }) { - try { - return new HibernateDatastore([ - 'dataSource.dbCreate' : 'create-drop', - 'hibernate.generatedDomainClasses' : false, - 'grails.gorm.multiTenancy.mode' : MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR, - 'grails.gorm.multiTenancy.tenantResolver': new SystemPropertyTenantResolver(), - ], group as Class[]) - } catch (Exception ignored) { - // a domain that needs another configuration is booted by default below - } - } - // the same create-drop the no-argument constructor applies, which resolves the SQL types the records hold - return new HibernateDatastore(['dataSource.dbCreate': 'create-drop', 'hibernate.generatedDomainClasses': false], group as Class[]) - } - /** * Boots a group through the generated classes, which is what the comparison reads the mapping of: the entities, their properties and the * facets the generator decides from them. The tenant mode is the one the classic binder was booted in. */ private static HibernateDatastore bootGenerated(List<Class<?>> group) { Map<String, Object> config = [ - 'dataSource.url' : "jdbc:h2:mem:generatorDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), - 'dataSource.dbCreate' : 'create-drop', - 'hibernate.generatedDomainClasses': true, + 'dataSource.url' : "jdbc:h2:mem:generatorDiff${BOOTS.incrementAndGet()};LOCK_TIMEOUT=10000".toString(), + 'dataSource.dbCreate': 'create-drop', ] if (group.any { Class<?> type -> ClassUtils.isMultiTenant(type) }) { config['grails.gorm.multiTenancy.mode'] = MultiTenancySettings.MultiTenancyMode.DISCRIMINATOR
