diff --git a/README.md b/README.md index 48c32db..2e07db0 100755 --- a/README.md +++ b/README.md @@ -353,3 +353,4 @@ Modules with their own `pom.xml` that run plain Hibernate without the Spring Boo | [`cascade-types`](cascade-types/) | JPA cascade types and `orphanRemoval` in Hibernate 7: composition vs aggregation, `orphanRemoval` vs `CascadeType.REMOVE`, the `cascade = ALL` on `@ManyToOne` incident reproduced in three schemas, `@ManyToMany` / `@OneToOne` / `@ManyToOne` cases, the cost of cascading a 1,000-row delete, `@OnDelete`, and the same tests on Hibernate `8.0.0.CR1`; plain Hibernate on H2 (Hibernate `7.4.15.Final`) | | [`one-to-many`](one-to-many/) | `@OneToMany` in Hibernate 7: unidirectional join table vs `@JoinColumn` vs bidirectional `mappedBy`, the SQL each sends, why removing one child from a join-table `List` deletes and re-inserts the rest (and why a `mappedBy` List does not), the bidirectional sync helper, fetch defaults, N+1 fixes, `MultipleBagFetchException` and its three fixes, and the id-based `hashCode` trap; plain Hibernate on H2 (Hibernate `7.4.16.Final`) | | [`n-plus-one-guard`](n-plus-one-guard/) | Detecting N+1 queries automatically: Hibernate Statistics vs datasource-proxy (what each counts and what each misses), five fixes with statement counts, and a JUnit 6 `@MaxSelects` guard that fails a test with the full SQL list; plain Hibernate on H2 (Hibernate `7.4.16.Final`, datasource-proxy `1.11.1`) | +| [`enums`](enums/) | Enum mapping in Hibernate 7: `ORDINAL` vs `STRING` vs PostgreSQL native enum vs `AttributeConverter` vs JPA 3.2 `@EnumeratedValue`, the DDL each creates, what release 2 reads and writes after a constant is inserted, appended or renamed, `hbm2ddl=update` limits and the migration each change needs; plain Hibernate on H2 and PostgreSQL 18 (Hibernate `7.4.17.Final`) | diff --git a/enums/README.md b/enums/README.md new file mode 100644 index 0000000..527ddff --- /dev/null +++ b/enums/README.md @@ -0,0 +1,38 @@ +# enums + +Companion module for the ankurm.com article **Enum Mapping in Hibernate 7: The ORDINAL Trap, STRING, PostgreSQL Native Enums and Converters**. +Every SQL statement, error message and row in the article comes from a test here; each test writes what it observed to `output/` and asserts the same facts. +Plain Hibernate on an in-memory H2 and on a local PostgreSQL 18: no Spring, no Docker needed. + +## Versions + +| Component | Version | Notes | +|---|---|---| +| Hibernate ORM | `7.4.17.Final` | newest 7.x GA in `maven-metadata.xml` on 2026-11-19 (`8.0.0.CR1` is listed after it but is not GA) | +| Jakarta Persistence | `3.2.0` | `@EnumeratedValue` is new in this version | +| H2 | `2.4.240` | in memory | +| PostgreSQL server / driver | `18.6` / `42.7.14` | server from the zonky embedded binaries, see `scripts/start-postgres.sh` | +| JUnit / AssertJ | `6.0.3` / `3.27.7` | | +| Java | `25` (Temurin 25.0.5.1) | | + +## Run + +```bash +./scripts/start-postgres.sh # throwaway PostgreSQL 18.6 on 127.0.0.1:55432 (skip if you have your own: -Dpg.host / -Dpg.port) +./scripts/run-all.sh # or: mvn clean test +``` + +## Tests and what they write + +| Test | Output | Question it answers | +|---|---|---| +| `T01_DdlTest` | `output/01-ddl.txt` | Which column type and check constraint does each mapping make Hibernate create, on H2 and PostgreSQL? | +| `T02_ReleaseTest` | `output/02-release-two.txt` | Release 1 wrote NEW/PAID/SHIPPED; release 2 inserts, appends or renames a constant. What does it read, and can it write the new value? | +| `T03_NativeEnumTest` | `output/03-native-enum.txt` | PostgreSQL native enum: ordering, `ALTER TYPE ... ADD / RENAME / DROP VALUE`, the in-transaction trap | +| `T03_NativeEnumTest` | `output/04-prefer-native.txt` | What does `hibernate.type.prefer_native_enum_types` change for plain `@Enumerated(STRING)`? | +| `T04_UpdateTest` | `output/05-hbm2ddl-update.txt` | Does `hbm2ddl.auto=update` fix the schema after a constant is added? | +| `T05_FixTest` | `output/06-migrations.txt` | The hand-written migration each change needs, and release 2 afterwards | +| `T06_QueryTest` | `output/07-queries.txt` | SQL sent for HQL on enums, `ORDER BY` per mapping, and a bad value in the column | +| `T07_PreferNativeAssertTest` | (assertions only) | `prefer_native_enum_types` really switches PostgreSQL to a native type | + +[`Variants`](src/main/java/com/ankurm/enums/Variants.java) holds every mapping as a small entity over the same table `orders(id, status)`. "V1" is release 1; "Mid" / "App" / "Ren" are release 2 with a constant inserted in the middle, appended, or renamed. diff --git a/enums/output/01-ddl.txt b/enums/output/01-ddl.txt new file mode 100644 index 0000000..37ffc43 --- /dev/null +++ b/enums/output/01-ddl.txt @@ -0,0 +1,43 @@ +# What DDL does each enum mapping produce? (Enum: NEW, PAID, SHIPPED; table orders(id, status)) +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== H2 +-- no @Enumerated (JPA default) + column type: TINYINT + check: "STATUS" BETWEEN 0 AND 2 +-- @Enumerated(ORDINAL) + column type: TINYINT + check: "STATUS" BETWEEN 0 AND 2 +-- @Enumerated(STRING) + column type: ENUM +-- @Enumerated(STRING) + @JdbcTypeCode(NAMED_ENUM) + column type: CHARACTER VARYING +-- @Convert(AttributeConverter) + column type: CHARACTER VARYING + check: "STATUS" IN('P', 'S', 'N') +-- @EnumeratedValue + @Enumerated(STRING) + column type: CHARACTER VARYING + check: "STATUS" IN('P', 'S', 'N') + +== PostgreSQL 18 +-- no @Enumerated (JPA default) + column type: smallint + check: CHECK (((status >= 0) AND (status <= 2))) +-- @Enumerated(ORDINAL) + column type: smallint + check: CHECK (((status >= 0) AND (status <= 2))) +-- @Enumerated(STRING) + column type: character varying(255) + check: CHECK (((status)::text = ANY ((ARRAY['NEW'::character varying, 'PAID'::character varying, 'SHIPPED'::character varying])::text[]))) +-- @Enumerated(STRING) + @JdbcTypeCode(NAMED_ENUM) + column type: statusv1 + enum labels: NEW, PAID, SHIPPED +-- @Convert(AttributeConverter) + column type: character varying(255) + check: CHECK (((status)::text = ANY ((ARRAY['P'::character varying, 'S'::character varying, 'N'::character varying])::text[]))) +-- @EnumeratedValue + @Enumerated(STRING) + column type: character varying(255) + check: CHECK (((status)::text = ANY ((ARRAY['P'::character varying, 'S'::character varying, 'N'::character varying])::text[]))) + +== @EnumeratedValue on a String code, without @Enumerated(STRING) +org.hibernate.MappingException: @EnumeratedValue for EnumType.ORDINAL must be placed on a field whose type is byte, short, or int: com.ankurm.enums.Variants$EvV1.code diff --git a/enums/output/02-release-two.txt b/enums/output/02-release-two.txt new file mode 100644 index 0000000..d53c989 --- /dev/null +++ b/enums/output/02-release-two.txt @@ -0,0 +1,86 @@ +# Release 1 wrote NEW, PAID, SHIPPED. Release 2 changes the enum; hbm2ddl = none +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== H2 +-- ORDINAL, CANCELLED inserted in the middle (release 2 enum: NEW, CANCELLED, PAID, SHIPPED) + stored by release 1 : [1 | 0, 2 | 1, 3 | 2] + release 2 reads : [NEW, CANCELLED, PAID] + release 2 writes SHIPPED : FAILS org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException + Check constraint violation: "CONSTRAINT_8: "; SQL statement: +-- ORDINAL, CANCELLED appended (release 2 enum: NEW, PAID, SHIPPED, CANCELLED) + stored by release 1 : [1 | 0, 2 | 1, 3 | 2] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException + Check constraint violation: "CONSTRAINT_8: "; SQL statement: +-- ORDINAL, PAID renamed PAYMENT_RECEIVED (release 2 enum: NEW, PAYMENT_RECEIVED, SHIPPED) + stored by release 1 : [1 | 0, 2 | 1, 3 | 2] + release 2 reads : [NEW, PAYMENT_RECEIVED, SHIPPED] + release 2 writes PAYMENT_RECEIVED : OK, stored [1] +-- STRING, CANCELLED inserted in the middle (release 2 enum: NEW, CANCELLED, PAID, SHIPPED) + stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.DataException <- org.h2.jdbc.JdbcSQLDataException + Value not permitted for column "('NEW', 'PAID', 'SHIPPED')": "CANCELLED"; SQL statement: +-- STRING, CANCELLED appended (release 2 enum: NEW, PAID, SHIPPED, CANCELLED) + stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.DataException <- org.h2.jdbc.JdbcSQLDataException + Value not permitted for column "('NEW', 'PAID', 'SHIPPED')": "CANCELLED"; SQL statement: +-- STRING, PAID renamed PAYMENT_RECEIVED (release 2 enum: NEW, PAYMENT_RECEIVED, SHIPPED) + stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED] + release 2 reads : FAILS java.lang.IllegalArgumentException + No enum constant com.ankurm.enums.Variants.StatusRen.PAID + release 2 writes PAYMENT_RECEIVED : FAILS org.hibernate.exception.DataException <- org.h2.jdbc.JdbcSQLDataException + Value not permitted for column "('NEW', 'PAID', 'SHIPPED')": "PAYMENT_RECEIVED"; SQL statement: +-- CONVERTER (codes N/P/S), CANCELLED inserted + PAID renamed (release 2 enum: NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED) + stored by release 1 : [1 | N, 2 | P, 3 | S] + release 2 reads : [NEW, PAYMENT_RECEIVED, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException + Check constraint violation: "CONSTRAINT_8: "; SQL statement: +-- @EnumeratedValue (codes N/P/S), CANCELLED inserted + PAID renamed (release 2 enum: NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED) + stored by release 1 : [1 | N, 2 | P, 3 | S] + release 2 reads : [NEW, PAYMENT_RECEIVED, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException + Check constraint violation: "CONSTRAINT_8: "; SQL statement: + +== PostgreSQL 18 +-- ORDINAL, CANCELLED inserted in the middle (release 2 enum: NEW, CANCELLED, PAID, SHIPPED) + stored by release 1 : [1 | 0, 2 | 1, 3 | 2] + release 2 reads : [NEW, CANCELLED, PAID] + release 2 writes SHIPPED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- ORDINAL, CANCELLED appended (release 2 enum: NEW, PAID, SHIPPED, CANCELLED) + stored by release 1 : [1 | 0, 2 | 1, 3 | 2] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- ORDINAL, PAID renamed PAYMENT_RECEIVED (release 2 enum: NEW, PAYMENT_RECEIVED, SHIPPED) + stored by release 1 : [1 | 0, 2 | 1, 3 | 2] + release 2 reads : [NEW, PAYMENT_RECEIVED, SHIPPED] + release 2 writes PAYMENT_RECEIVED : OK, stored [1] +-- STRING, CANCELLED inserted in the middle (release 2 enum: NEW, CANCELLED, PAID, SHIPPED) + stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- STRING, CANCELLED appended (release 2 enum: NEW, PAID, SHIPPED, CANCELLED) + stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- STRING, PAID renamed PAYMENT_RECEIVED (release 2 enum: NEW, PAYMENT_RECEIVED, SHIPPED) + stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED] + release 2 reads : FAILS java.lang.IllegalArgumentException + No enum constant com.ankurm.enums.Variants.StatusRen.PAID + release 2 writes PAYMENT_RECEIVED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- CONVERTER (codes N/P/S), CANCELLED inserted + PAID renamed (release 2 enum: NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED) + stored by release 1 : [1 | N, 2 | P, 3 | S] + release 2 reads : [NEW, PAYMENT_RECEIVED, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- @EnumeratedValue (codes N/P/S), CANCELLED inserted + PAID renamed (release 2 enum: NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED) + stored by release 1 : [1 | N, 2 | P, 3 | S] + release 2 reads : [NEW, PAYMENT_RECEIVED, SHIPPED] + release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException + ERROR: new row for relation "orders" violates check constraint "orders_status_check" diff --git a/enums/output/03-native-enum.txt b/enums/output/03-native-enum.txt new file mode 100644 index 0000000..8dd9f9e --- /dev/null +++ b/enums/output/03-native-enum.txt @@ -0,0 +1,21 @@ +# PostgreSQL native enum (CREATE TYPE ... AS ENUM): ordering, ALTER TYPE, and what cannot be undone +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== Ordering. Enum declared as NEW, PAID, SHIPPED, CANCELLED (the order a workflow would use) +-- type created by Hibernate (hbm2ddl = create) + enum labels in sort order: [CANCELLED, NEW, PAID, SHIPPED] + order by status : [CANCELLED, NEW, PAID, SHIPPED] +-- type written by hand, labels in workflow order + order by status : [NEW, PAID, SHIPPED, CANCELLED] + +== Release 2 needs CANCELLED, but the database type was created from release 1's NEW, PAID, SHIPPED + write CANCELLED before ALTER TYPE : org.hibernate.exception.DataException <- org.postgresql.util.PSQLException + ERROR: invalid input value for enum statusv1: "CANCELLED" + after ALTER TYPE statusv1 ADD VALUE 'CANCELLED' : OK, rows [1 | PAID, 10 | CANCELLED] + labels now (appended at the end): [NEW, PAID, SHIPPED, CANCELLED] + ADD VALUE 'ON_HOLD' BEFORE 'PAID' : labels [NEW, ON_HOLD, PAID, SHIPPED, CANCELLED] + RENAME VALUE 'PAID' TO 'PAYMENT_RECEIVED' : row 1 is now [PAYMENT_RECEIVED] + ALTER TYPE ... DROP VALUE : ERROR: dropping an enum value is not implemented + +== ADD VALUE inside a transaction: usable only after commit + ADD VALUE then INSERT using it in ONE transaction : ERROR: unsafe use of new value "CANCELLED" of enum type statusv1 diff --git a/enums/output/04-prefer-native.txt b/enums/output/04-prefer-native.txt new file mode 100644 index 0000000..284f35b --- /dev/null +++ b/enums/output/04-prefer-native.txt @@ -0,0 +1,15 @@ +# hibernate.type.prefer_native_enum_types on plain @Enumerated(STRING) +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== H2 +-- prefer_native_enum_types=false + column type: ENUM +-- prefer_native_enum_types=true + column type: ENUM + +== PostgreSQL 18 +-- prefer_native_enum_types=false + column type: character varying(255) + check: CHECK (((status)::text = ANY ((ARRAY['NEW'::character varying, 'PAID'::character varying, 'SHIPPED'::character varying])::text[]))) +-- prefer_native_enum_types=true + column type: statusv1 diff --git a/enums/output/05-hbm2ddl-update.txt b/enums/output/05-hbm2ddl-update.txt new file mode 100644 index 0000000..71d2d7c --- /dev/null +++ b/enums/output/05-hbm2ddl-update.txt @@ -0,0 +1,24 @@ +# Adding CANCELLED, then starting release 2 with hbm2ddl=update: is the schema fixed? +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== H2 +-- ORDINAL + after update: column type: TINYINT + after update: check: "STATUS" BETWEEN 0 AND 2 + write CANCELLED : FAILS Check constraint violation: "CONSTRAINT_8: "; SQL statement: +-- STRING + after update: column type: ENUM + write CANCELLED : FAILS Value not permitted for column "('NEW', 'PAID', 'SHIPPED')": "CANCELLED"; SQL statement: + +== PostgreSQL 18 +-- ORDINAL + after update: column type: smallint + after update: check: CHECK (((status >= 0) AND (status <= 2))) + write CANCELLED : FAILS ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- STRING + after update: column type: character varying(255) + after update: check: CHECK (((status)::text = ANY ((ARRAY['NEW'::character varying, 'PAID'::character varying, 'SHIPPED'::character varying])::text[]))) + write CANCELLED : FAILS ERROR: new row for relation "orders" violates check constraint "orders_status_check" +-- NAMED_ENUM + after update: column type: statusv1 + write CANCELLED : FAILS ERROR: invalid input value for enum statusv1: "CANCELLED" diff --git a/enums/output/06-migrations.txt b/enums/output/06-migrations.txt new file mode 100644 index 0000000..09fee00 --- /dev/null +++ b/enums/output/06-migrations.txt @@ -0,0 +1,21 @@ +# The migration each enum change needs (PostgreSQL 18), and release 2 afterwards +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== ORDINAL: insert CANCELLED between NEW and PAID + migration : drop check; UPDATE orders SET status = status + 1 WHERE status >= 1; add check (status between 0 and 3) + stored : [1 | 0, 2 | 2, 3 | 3] + release 2 reads : [NEW, PAID, SHIPPED] + release 2 writes CANCELLED : OK, stored [1] + +== STRING: append CANCELLED + migration : drop check; add check (status in ('NEW', 'PAID', 'SHIPPED', 'CANCELLED')) + release 2 writes CANCELLED : OK, rows [1 | PAID, 10 | CANCELLED] + +== STRING: rename PAID to PAYMENT_RECEIVED + migration : drop check; UPDATE ... SET status = 'PAYMENT_RECEIVED' WHERE status = 'PAID'; add check + release 2 reads : [NEW, PAYMENT_RECEIVED] + +== CONVERTER or @EnumeratedValue: insert CANCELLED and rename PAID (codes unchanged) + migration : drop check; add check (status in ('N', 'C', 'P', 'S')); no UPDATE, no data touched + release 2 reads : [PAYMENT_RECEIVED] + release 2 writes CANCELLED : OK, stored [C] diff --git a/enums/output/07-queries.txt b/enums/output/07-queries.txt new file mode 100644 index 0000000..9d241fb --- /dev/null +++ b/enums/output/07-queries.txt @@ -0,0 +1,26 @@ +# HQL on enum attributes: SQL sent, ORDER BY, and a bad value in the column (PostgreSQL 18) +# Hibernate ORM 7.4.17.Final, H2 2.4.240 and PostgreSQL 18.6, JDK 25 + +== The SQL Hibernate sends for from X o where o.status = :s (parameter = PAID / PAYMENT_RECEIVED) +-- ORDINAL + sql> select ov1_0.id,ov1_0.status from orders ov1_0 where ov1_0.status=? +-- STRING + sql> select sv1_0.id,sv1_0.status from orders sv1_0 where sv1_0.status=? +-- NAMED_ENUM + sql> select nv1_0.id,nv1_0.status from orders nv1_0 where nv1_0.status=? +-- CONVERTER + sql> select cv1_0.id,cv1_0.status from orders cv1_0 where cv1_0.status=? +-- CONVERTER, enum literal in the HQL text + sql> select cv1_0.id,cv1_0.status from orders cv1_0 where cv1_0.status='P' + +== ORDER BY status on NEW, SHIPPED, CANCELLED, PAID stored under each mapping + ORDINAL (enum NEW, PAID, SHIPPED, CANCELLED) : [NEW, PAID, SHIPPED, CANCELLED] + STRING : [CANCELLED, NEW, PAID, SHIPPED] + CONVERTER (codes C, N, P, S, stored values) : [C, N, P, S] + +== A value the enum does not know, in the column + insert 'X' with Hibernate's generated check in place : ERROR: new row for relation "orders" violates check constraint "orders_status_check" + read after the check is dropped and 'X' is inserted : jakarta.persistence.PersistenceException <- java.lang.IllegalArgumentException + Unknown CodedV1 code 'X' + ORDINAL with the check dropped and ordinal 7 stored : java.lang.ArrayIndexOutOfBoundsException + Index 7 out of bounds for length 3 diff --git a/enums/pom.xml b/enums/pom.xml new file mode 100644 index 0000000..82faa4e --- /dev/null +++ b/enums/pom.xml @@ -0,0 +1,70 @@ + + + 4.0.0 + + com.ankurm + enums + 1.0.0 + enums + Enum mapping in Hibernate 7: ORDINAL vs STRING vs native enum types vs AttributeConverter vs @EnumeratedValue, and what each does when the enum changes (plain Hibernate on H2 and PostgreSQL) + + + 25 + UTF-8 + + 7.4.17.Final + 3.2.0 + + + + + org.hibernate.orm + hibernate-core + ${hibernate.version} + + + jakarta.persistence + jakarta.persistence-api + ${persistence.version} + + + com.h2database + h2 + 2.4.240 + + + org.postgresql + postgresql + 42.7.14 + + + org.junit.jupiter + junit-jupiter + 6.0.3 + test + + + org.assertj + assertj-core + 3.27.7 + test + + + + + + + maven-surefire-plugin + 3.6.0 + + -Xmx512m + + ${hibernate.version} + + + + + + diff --git a/enums/scripts/run-all.sh b/enums/scripts/run-all.sh new file mode 100755 index 0000000..bf9a11c --- /dev/null +++ b/enums/scripts/run-all.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. Needs JDK 25, Maven 3.9, network access to Maven Central, and a PostgreSQL on +# 127.0.0.1:55432 (user postgres, trust auth). scripts/start-postgres.sh starts one without Docker. +# ./scripts/start-postgres.sh && ./scripts/run-all.sh +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -B clean test +ls -1 output diff --git a/enums/scripts/start-postgres.sh b/enums/scripts/start-postgres.sh new file mode 100755 index 0000000..fc20566 --- /dev/null +++ b/enums/scripts/start-postgres.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Starts a throwaway PostgreSQL server for the tests, without Docker. Idempotent. +# PostgreSQL 18.6 : zonky embedded-postgres-binaries-linux-amd64 18.6.0 from Maven Central (initdb, pg_ctl, postgres), port 55432 +# PostgreSQL refuses to run as root, so this creates a throwaway OS user (pgj). Run it as root in a disposable sandbox. +set -euo pipefail +BASE="${BASE:-/tmp/work/dbs}" +PGPORT="${PGPORT:-55432}" +mkdir -p "$BASE/pg" +id pgj >/dev/null 2>&1 || useradd -m pgj +if [ ! -x "$BASE/pg/pg/bin/postgres" ]; then + curl -sSfL -o "$BASE/pg/pg.jar" \ + https://repo1.maven.org/maven2/io/zonky/test/postgres/embedded-postgres-binaries-linux-amd64/18.6.0/embedded-postgres-binaries-linux-amd64-18.6.0.jar + (cd "$BASE/pg" && unzip -o -q pg.jar && mkdir -p pg && tar -xJf postgres-linux-x86_64.txz -C pg) +fi +chmod -R a+rX "$BASE/pg" +if [ ! -f "$BASE/pg/data/PG_VERSION" ]; then + mkdir -p "$BASE/pg/data"; chown pgj "$BASE/pg/data" + su pgj -c "cd /tmp && $BASE/pg/pg/bin/initdb -D $BASE/pg/data -U postgres -A trust -E UTF8 >/dev/null" +fi +su pgj -c "$BASE/pg/pg/bin/pg_ctl -D $BASE/pg/data -o '-p $PGPORT -k /tmp' -l $BASE/pg/data/pg.log -w start" || true +psql -h 127.0.0.1 -p "$PGPORT" -U postgres -Atc 'select version()' diff --git a/enums/src/main/java/com/ankurm/enums/Variants.java b/enums/src/main/java/com/ankurm/enums/Variants.java new file mode 100644 index 0000000..e9633ff --- /dev/null +++ b/enums/src/main/java/com/ankurm/enums/Variants.java @@ -0,0 +1,526 @@ +package com.ankurm.enums; + +import jakarta.persistence.*; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +/** + * Every mapping this module compares, as small entities that all map to the SAME table, {@code orders(id, status)}. + * "V1" is what shipped; "Mid" and "App" are the next release with {@code CANCELLED} inserted in the middle or appended; + * "Ren" renames {@code PAID}. Opening a second SessionFactory with the next release's classes against the data the first + * one wrote is how the tests reproduce a deployment. Public fields: the mapping is all there is to read. + */ +public final class Variants { + + private Variants() { + } + + /** What every variant exposes so the tests can treat them alike. */ + public interface Row { + Long id(); + + /** The enum constant name the entity currently holds, or null. */ + String statusName(); + } + + // ---- the enums --------------------------------------------------------------------------------------------- + + public enum StatusV1 { NEW, PAID, SHIPPED } + + /** CANCELLED inserted in the middle (alphabetical or "logical" order, as people do). */ + public enum StatusMid { NEW, CANCELLED, PAID, SHIPPED } + + /** CANCELLED appended at the end. */ + public enum StatusApp { NEW, PAID, SHIPPED, CANCELLED } + + /** PAID renamed. */ + public enum StatusRen { NEW, PAYMENT_RECEIVED, SHIPPED } + + /** Enum carrying its own stable code, used with a converter. */ + public enum CodedV1 { + NEW("N"), PAID("P"), SHIPPED("S"); + + public final String code; + + CodedV1(String code) { + this.code = code; + } + + public static CodedV1 of(String code) { + for (CodedV1 s : values()) { + if (s.code.equals(code)) { + return s; + } + } + throw new IllegalArgumentException("Unknown CodedV1 code '" + code + "'"); + } + } + + /** Same stable codes, CANCELLED inserted in the middle AND PAID's constant renamed: the codes do not move. */ + public enum CodedMid { + NEW("N"), CANCELLED("C"), PAYMENT_RECEIVED("P"), SHIPPED("S"); + + public final String code; + + CodedMid(String code) { + this.code = code; + } + + public static CodedMid of(String code) { + for (CodedMid s : values()) { + if (s.code.equals(code)) { + return s; + } + } + throw new IllegalArgumentException("Unknown CodedMid code '" + code + "'"); + } + } + + /** JPA 3.2 {@code @EnumeratedValue}: the code lives on the enum and no converter is needed. */ + public enum EvV1 { + NEW("N"), PAID("P"), SHIPPED("S"); + + @EnumeratedValue + private final String code; + + EvV1(String code) { + this.code = code; + } + } + + public enum EvMid { + NEW("N"), CANCELLED("C"), PAYMENT_RECEIVED("P"), SHIPPED("S"); + + @EnumeratedValue + private final String code; + + EvMid(String code) { + this.code = code; + } + } + + // ---- converters -------------------------------------------------------------------------------------------- + + @Converter + public static class CodedV1Converter implements AttributeConverter { + @Override + public String convertToDatabaseColumn(CodedV1 v) { + return v == null ? null : v.code; + } + + @Override + public CodedV1 convertToEntityAttribute(String db) { + return db == null ? null : CodedV1.of(db); + } + } + + @Converter + public static class CodedMidConverter implements AttributeConverter { + @Override + public String convertToDatabaseColumn(CodedMid v) { + return v == null ? null : v.code; + } + + @Override + public CodedMid convertToEntityAttribute(String db) { + return db == null ? null : CodedMid.of(db); + } + } + + // ---- ORDINAL ----------------------------------------------------------------------------------------------- + + @Entity(name = "OrdV1") + @Table(name = "orders") + public static class OrdV1 implements Row { + @Id + public Long id; + @Enumerated(EnumType.ORDINAL) + public StatusV1 status; + + public OrdV1() { + } + + public OrdV1(long id, StatusV1 s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + /** No @Enumerated at all: JPA says the default is ORDINAL. */ + @Entity(name = "OrdDefault") + @Table(name = "orders") + public static class OrdDefault implements Row { + @Id + public Long id; + public StatusV1 status; + + public OrdDefault() { + } + + public OrdDefault(long id, StatusV1 s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "OrdMid") + @Table(name = "orders") + public static class OrdMid implements Row { + @Id + public Long id; + @Enumerated(EnumType.ORDINAL) + public StatusMid status; + + public OrdMid() { + } + + public OrdMid(long id, StatusMid s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + /** ORDINAL with PAID renamed: the position does not move, so nothing stored changes meaning. */ + @Entity(name = "OrdRen") + @Table(name = "orders") + public static class OrdRen implements Row { + @Id + public Long id; + @Enumerated(EnumType.ORDINAL) + public StatusRen status; + + public OrdRen() { + } + + public OrdRen(long id, StatusRen s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "OrdApp") + @Table(name = "orders") + public static class OrdApp implements Row { + @Id + public Long id; + @Enumerated(EnumType.ORDINAL) + public StatusApp status; + + public OrdApp() { + } + + public OrdApp(long id, StatusApp s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + // ---- STRING ------------------------------------------------------------------------------------------------ + + @Entity(name = "StrV1") + @Table(name = "orders") + public static class StrV1 implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + public StatusV1 status; + + public StrV1() { + } + + public StrV1(long id, StatusV1 s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "StrMid") + @Table(name = "orders") + public static class StrMid implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + public StatusMid status; + + public StrMid() { + } + + public StrMid(long id, StatusMid s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "StrRen") + @Table(name = "orders") + public static class StrRen implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + public StatusRen status; + + public StrRen() { + } + + public StrRen(long id, StatusRen s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "StrApp") + @Table(name = "orders") + public static class StrApp implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + public StatusApp status; + + public StrApp() { + } + + public StrApp(long id, StatusApp s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + /** {@code @EnumeratedValue} with a String code but no {@code @Enumerated(STRING)}: Hibernate refuses to start. */ + @Entity(name = "EvBad") + @Table(name = "orders") + public static class EvBad { + @Id + public Long id; + public EvV1 status; + } + + // ---- native enum type (PostgreSQL CREATE TYPE ... AS ENUM) -------------------------------------------------- + + @Entity(name = "NatV1") + @Table(name = "orders") + public static class NatV1 implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + @JdbcTypeCode(SqlTypes.NAMED_ENUM) + public StatusV1 status; + + public NatV1() { + } + + public NatV1(long id, StatusV1 s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "NatApp") + @Table(name = "orders") + public static class NatApp implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + @JdbcTypeCode(SqlTypes.NAMED_ENUM) + public StatusApp status; + + public NatApp() { + } + + public NatApp(long id, StatusApp s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + // ---- AttributeConverter ------------------------------------------------------------------------------------ + + @Entity(name = "ConvV1") + @Table(name = "orders") + public static class ConvV1 implements Row { + @Id + public Long id; + @Convert(converter = CodedV1Converter.class) + public CodedV1 status; + + public ConvV1() { + } + + public ConvV1(long id, CodedV1 s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "ConvMid") + @Table(name = "orders") + public static class ConvMid implements Row { + @Id + public Long id; + @Convert(converter = CodedMidConverter.class) + public CodedMid status; + + public ConvMid() { + } + + public ConvMid(long id, CodedMid s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + // ---- JPA 3.2 @EnumeratedValue ------------------------------------------------------------------------------ + + @Entity(name = "EvEntV1") + @Table(name = "orders") + public static class EvEntV1 implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + public EvV1 status; + + public EvEntV1() { + } + + public EvEntV1(long id, EvV1 s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } + + @Entity(name = "EvEntMid") + @Table(name = "orders") + public static class EvEntMid implements Row { + @Id + public Long id; + @Enumerated(EnumType.STRING) + public EvMid status; + + public EvEntMid() { + } + + public EvEntMid(long id, EvMid s) { + this.id = id; + this.status = s; + } + + public Long id() { + return id; + } + + public String statusName() { + return status == null ? null : status.name(); + } + } +} diff --git a/enums/src/test/java/com/ankurm/enums/Db.java b/enums/src/test/java/com/ankurm/enums/Db.java new file mode 100644 index 0000000..89e7c7e --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/Db.java @@ -0,0 +1,242 @@ +package com.ankurm.enums; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.resource.jdbc.spi.StatementInspector; + +/** + * Plain Hibernate bootstrap (no Spring, no persistence.xml) on an in-memory H2 or on a throwaway schema of a local + * PostgreSQL, plus helpers that record the SQL Hibernate sends. {@link #attach} opens a SECOND SessionFactory on the + * same database with different entity classes, which is how the tests play "the next release against yesterday's rows". + */ +final class Db implements AutoCloseable { + + enum Kind { H2, PG } + + static final String PG_HOST = System.getProperty("pg.host", "127.0.0.1"); + static final String PG_PORT = System.getProperty("pg.port", "55432"); + + /** Every SQL string Hibernate prepares, in order (raw JDBC issued by the tests is not recorded). */ + private static final List LOG = new ArrayList<>(); + + public static class Recorder implements StatementInspector { + @Override + public String inspect(String sql) { + synchronized (LOG) { + LOG.add(sql.replaceAll("\\s+", " ").trim()); + } + return sql; + } + } + + private final SessionFactory sf; + final Kind kind; + private final String url; + private final String schema; + private final boolean owner; + + private Db(SessionFactory sf, Kind kind, String url, String schema, boolean owner) { + this.sf = sf; + this.kind = kind; + this.url = url; + this.schema = schema; + this.owner = owner; + } + + static boolean pgAvailable() { + try (Connection c = DriverManager.getConnection("jdbc:postgresql://" + PG_HOST + ":" + PG_PORT + "/postgres", "postgres", "")) { + return c.isValid(2); + } + catch (Exception e) { + return false; + } + } + + static Db open(Kind kind, Class... entities) { + return open(kind, "create-drop", Map.of(), entities); + } + + static Db open(Kind kind, String hbm2ddl, Map extra, Class... entities) { + String url; + String schema = null; + if (kind == Kind.H2) { + url = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1"; + } + else { + schema = "t_" + UUID.randomUUID().toString().replace("-", ""); + url = "jdbc:postgresql://" + PG_HOST + ":" + PG_PORT + "/postgres?currentSchema=" + schema; + rawPg("create schema " + schema); + } + return build(kind, url, schema, true, hbm2ddl, extra, entities); + } + + /** A second SessionFactory on the same database and schema, with its own entity classes. */ + Db attach(String hbm2ddl, Map extra, Class... entities) { + return build(kind, url, schema, false, hbm2ddl, extra, entities); + } + + private static Db build(Kind kind, String url, String schema, boolean owner, String hbm2ddl, + Map extra, Class[] entities) { + StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder() + .applySetting("hibernate.connection.url", url) + .applySetting("hibernate.connection.username", kind == Kind.H2 ? "sa" : "postgres") + .applySetting("hibernate.connection.password", "") + .applySetting("hibernate.hbm2ddl.auto", hbm2ddl) + .applySetting("hibernate.session_factory.statement_inspector", Recorder.class.getName()); + extra.forEach(b::applySetting); + StandardServiceRegistry registry = b.build(); + MetadataSources sources = new MetadataSources(registry); + for (Class e : entities) { + sources.addAnnotatedClass(e); + } + return new Db(sources.buildMetadata().buildSessionFactory(), kind, url, schema, owner); + } + + private static void rawPg(String sql) { + try (Connection c = DriverManager.getConnection("jdbc:postgresql://" + PG_HOST + ":" + PG_PORT + "/postgres", "postgres", ""); + Statement st = c.createStatement()) { + st.execute(sql); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + } + + SessionFactory sf() { + return sf; + } + + /** Runs {@code work} in its own session and transaction. */ + T tx(Function work) { + try (Session s = sf.openSession()) { + var t = s.beginTransaction(); + try { + T r = work.apply(s); + t.commit(); + return r; + } + catch (RuntimeException e) { + if (t.isActive()) { + t.rollback(); + } + throw e; + } + } + } + + void txv(Consumer work) { + tx(s -> { + work.accept(s); + return null; + }); + } + + /** Runs the action and returns the SQL Hibernate prepared while it ran. */ + static List sql(Runnable action) { + synchronized (LOG) { + LOG.clear(); + } + action.run(); + synchronized (LOG) { + return new ArrayList<>(LOG); + } + } + + /** Raw JDBC query, each row rendered as {@code a | b | c}. */ + List rows(String sql) { + return tx(s -> s.doReturningWork(cn -> { + List out = new ArrayList<>(); + try (var st = cn.createStatement(); ResultSet rs = st.executeQuery(sql)) { + ResultSetMetaData md = rs.getMetaData(); + while (rs.next()) { + StringBuilder b = new StringBuilder(); + for (int i = 1; i <= md.getColumnCount(); i++) { + if (i > 1) { + b.append(" | "); + } + b.append(rs.getObject(i)); + } + out.add(b.toString()); + } + } + return out; + })); + } + + /** Raw JDBC statement (DDL or DML), invisible to the SQL recorder. */ + void exec(String sql) { + txv(s -> s.doWork(cn -> { + try (var st = cn.createStatement()) { + st.execute(sql); + } + })); + } + + /** The type, nullability and (PostgreSQL / H2) check constraints of orders.status, as the database reports them. */ + List describeStatus() { + List out = new ArrayList<>(); + if (kind == Kind.PG) { + out.addAll(rows("select 'column type: ' || format_type(a.atttypid, a.atttypmod) from pg_attribute a " + + "join pg_class c on c.oid = a.attrelid join pg_namespace n on n.oid = c.relnamespace " + + "where n.nspname = '" + schema + "' and c.relname = 'orders' and a.attname = 'status'")); + out.addAll(rows("select 'check: ' || pg_get_constraintdef(k.oid) from pg_constraint k " + + "join pg_class c on c.oid = k.conrelid join pg_namespace n on n.oid = c.relnamespace " + + "where n.nspname = '" + schema + "' and c.relname = 'orders' and k.contype = 'c' order by 1")); + } + else { + out.addAll(rows("select 'column type: ' || data_type from information_schema.columns " + + "where table_name = 'ORDERS' and column_name = 'STATUS'")); + out.addAll(rows("select 'check: ' || cc.check_clause from information_schema.check_constraints cc " + + "join information_schema.table_constraints tc on tc.constraint_name = cc.constraint_name " + + "and tc.constraint_schema = cc.constraint_schema where tc.table_name = 'ORDERS' order by 1")); + } + return out; + } + + static Throwable root(Throwable t) { + while (t.getCause() != null && t.getCause() != t) { + t = t.getCause(); + } + return t; + } + + /** Exception chain on one line, class names only, so transcripts stay stable. */ + static String chain(Throwable t) { + StringBuilder sb = new StringBuilder(t.getClass().getName()); + Throwable c = t.getCause(); + while (c != null && c != t) { + sb.append(" <- ").append(c.getClass().getName()); + t = c; + c = c.getCause(); + } + return sb.toString(); + } + + static String firstLine(Throwable t) { + return String.valueOf(t.getMessage()).lines().findFirst().orElse(""); + } + + @Override + public void close() { + if (sf.isOpen()) { + sf.close(); + } + if (owner && kind == Kind.PG) { + rawPg("drop schema if exists " + schema + " cascade"); + } + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T01_DdlTest.java b/enums/src/test/java/com/ankurm/enums/T01_DdlTest.java new file mode 100644 index 0000000..3640e5c --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T01_DdlTest.java @@ -0,0 +1,71 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.*; +import java.util.List; +import org.hibernate.MappingException; +import org.junit.jupiter.api.Test; + +/** What column type and which check constraint each mapping makes Hibernate 7 create, on H2 and on PostgreSQL. */ +class T01_DdlTest { + + record Mapping(String label, Class entity) { + } + + static final List MAPPINGS = List.of( + new Mapping("no @Enumerated (JPA default)", OrdDefault.class), + new Mapping("@Enumerated(ORDINAL)", OrdV1.class), + new Mapping("@Enumerated(STRING)", StrV1.class), + new Mapping("@Enumerated(STRING) + @JdbcTypeCode(NAMED_ENUM)", NatV1.class), + new Mapping("@Convert(AttributeConverter)", ConvV1.class), + new Mapping("@EnumeratedValue + @Enumerated(STRING)", EvEntV1.class)); + + @Test + void ddlPerMapping() { + Transcript t = new Transcript("01-ddl", "What DDL does each enum mapping produce? (Enum: NEW, PAID, SHIPPED; table orders(id, status))"); + for (Db.Kind kind : Db.Kind.values()) { + if (kind == Db.Kind.PG && !Db.pgAvailable()) { + throw new IllegalStateException("PostgreSQL not reachable: run scripts/start-postgres.sh"); + } + t.heading(kind == Db.Kind.H2 ? "H2" : "PostgreSQL 18"); + for (Mapping m : MAPPINGS) { + try (Db db = Db.open(kind, m.entity())) { + t.line("-- " + m.label()); + List d = db.describeStatus(); + t.lines(d, " "); + if (m.entity() == OrdDefault.class || m.entity() == OrdV1.class) { + assertThat(d).anyMatch(x -> x.contains(kind == Db.Kind.PG ? "smallint" : "TINYINT")).anyMatch(x -> x.startsWith("check:")); + } + if (m.entity() == ConvV1.class || m.entity() == EvEntV1.class) { + assertThat(d).anyMatch(x -> x.startsWith("check:") && x.contains("'N'") && x.contains("'P'") && x.contains("'S'")); + } + if (kind == Db.Kind.PG && m.entity() == StrV1.class) { + assertThat(d).anyMatch(x -> x.startsWith("check:") && x.contains("'SHIPPED'")); + } + if (kind == Db.Kind.PG && m.entity() == NatV1.class) { + assertThat(d).contains("column type: statusv1").noneMatch(x -> x.startsWith("check:")); + } + if (kind == Db.Kind.H2 && m.entity() == StrV1.class) { + assertThat(d).containsExactly("column type: ENUM"); + } + if (kind == Db.Kind.PG && m.entity() == NatV1.class) { + t.lines(db.rows("select ' enum labels: ' || string_agg(e.enumlabel, ', ' order by e.enumsortorder) from pg_enum e " + + "join pg_type ty on ty.oid = e.enumtypid join pg_namespace n on n.oid = ty.typnamespace " + + "where ty.typname = 'statusv1' and n.nspname = current_schema()"), ""); + } + } + } + } + + t.heading("@EnumeratedValue on a String code, without @Enumerated(STRING)"); + try (Db db = Db.open(Db.Kind.H2, EvBad.class)) { + throw new AssertionError("expected MappingException"); + } + catch (MappingException ex) { + t.line(ex.getClass().getName() + ": " + ex.getMessage()); + assertThat(ex.getMessage()).contains("@EnumeratedValue for EnumType.ORDINAL must be placed on a field whose type is byte, short, or int"); + } + t.write(); + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T02_ReleaseTest.java b/enums/src/test/java/com/ankurm/enums/T02_ReleaseTest.java new file mode 100644 index 0000000..8dbdb2e --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T02_ReleaseTest.java @@ -0,0 +1,118 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.*; +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; +import org.junit.jupiter.api.Test; + +/** + * The deployment story. Release 1 writes three orders (NEW, PAID, SHIPPED). Release 2 changes the enum and opens a + * SECOND SessionFactory on the same database, without touching the schema (hbm2ddl = none, as in production). + * Each scenario records what release 2 reads and whether it can write the new constant. + */ +class T02_ReleaseTest { + + /** One mapping across two releases. {@code make1}/{@code make2} build an entity from (id, constant name). */ + record Scenario(String label, Class r1, BiFunction make1, Class r2, String entity2, + BiFunction make2, String newConstant, String change) { + } + + static final List SCENARIOS = List.of( + new Scenario("ORDINAL, CANCELLED inserted in the middle", OrdV1.class, + (id, n) -> new OrdV1(id, StatusV1.valueOf(n)), OrdMid.class, "OrdMid", + (id, n) -> new OrdMid(id, StatusMid.valueOf(n)), "SHIPPED", "NEW, CANCELLED, PAID, SHIPPED"), + new Scenario("ORDINAL, CANCELLED appended", OrdV1.class, + (id, n) -> new OrdV1(id, StatusV1.valueOf(n)), OrdApp.class, "OrdApp", + (id, n) -> new OrdApp(id, StatusApp.valueOf(n)), "CANCELLED", "NEW, PAID, SHIPPED, CANCELLED"), + new Scenario("ORDINAL, PAID renamed PAYMENT_RECEIVED", OrdV1.class, + (id, n) -> new OrdV1(id, StatusV1.valueOf(n)), OrdRen.class, "OrdRen", + (id, n) -> new OrdRen(id, StatusRen.valueOf(n)), "PAYMENT_RECEIVED", "NEW, PAYMENT_RECEIVED, SHIPPED"), + new Scenario("STRING, CANCELLED inserted in the middle", StrV1.class, + (id, n) -> new StrV1(id, StatusV1.valueOf(n)), StrMid.class, "StrMid", + (id, n) -> new StrMid(id, StatusMid.valueOf(n)), "CANCELLED", "NEW, CANCELLED, PAID, SHIPPED"), + new Scenario("STRING, CANCELLED appended", StrV1.class, + (id, n) -> new StrV1(id, StatusV1.valueOf(n)), StrApp.class, "StrApp", + (id, n) -> new StrApp(id, StatusApp.valueOf(n)), "CANCELLED", "NEW, PAID, SHIPPED, CANCELLED"), + new Scenario("STRING, PAID renamed PAYMENT_RECEIVED", StrV1.class, + (id, n) -> new StrV1(id, StatusV1.valueOf(n)), StrRen.class, "StrRen", + (id, n) -> new StrRen(id, StatusRen.valueOf(n)), "PAYMENT_RECEIVED", "NEW, PAYMENT_RECEIVED, SHIPPED"), + new Scenario("CONVERTER (codes N/P/S), CANCELLED inserted + PAID renamed", ConvV1.class, + (id, n) -> new ConvV1(id, CodedV1.valueOf(n)), ConvMid.class, "ConvMid", + (id, n) -> new ConvMid(id, CodedMid.valueOf(n)), "CANCELLED", "NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED"), + new Scenario("@EnumeratedValue (codes N/P/S), CANCELLED inserted + PAID renamed", EvEntV1.class, + (id, n) -> new EvEntV1(id, EvV1.valueOf(n)), EvEntMid.class, "EvEntMid", + (id, n) -> new EvEntMid(id, EvMid.valueOf(n)), "CANCELLED", "NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED")); + + @Test + void whatReleaseTwoSees() { + Transcript t = new Transcript("02-release-two", "Release 1 wrote NEW, PAID, SHIPPED. Release 2 changes the enum; hbm2ddl = none"); + java.util.Map res = new java.util.LinkedHashMap<>(); + for (Db.Kind kind : Db.Kind.values()) { + t.heading(kind == Db.Kind.H2 ? "H2" : "PostgreSQL 18"); + for (Scenario sc : SCENARIOS) { + t.line("-- " + sc.label() + " (release 2 enum: " + sc.change() + ")"); + try (Db db1 = Db.open(kind, sc.r1())) { + db1.txv(s -> { + s.persist(sc.make1().apply(1L, "NEW")); + s.persist(sc.make1().apply(2L, "PAID")); + s.persist(sc.make1().apply(3L, "SHIPPED")); + }); + t.line(" stored by release 1 : " + db1.rows("select id, status from orders order by id")); + try (Db db2 = db1.attach("none", java.util.Map.of(), sc.r2())) { + try { + List names = new ArrayList<>(); + db2.tx(s -> s.createSelectionQuery("from " + sc.entity2() + " o order by o.id", Row.class).getResultList()) + .forEach(r -> names.add(r.statusName())); + t.line(" release 2 reads : " + names); + res.put(kind + "|" + sc.label() + "|reads", names.toString()); + } + catch (RuntimeException ex) { + t.line(" release 2 reads : FAILS " + Db.chain(ex)); + res.put(kind + "|" + sc.label() + "|reads", "FAILS " + Db.root(ex).getMessage()); + t.line(" " + Db.firstLine(Db.root(ex))); + } + try { + db2.txv(s -> s.persist(sc.make2().apply(10L, sc.newConstant()))); + t.line(" release 2 writes " + sc.newConstant() + " : OK, stored " + db2.rows("select status from orders where id = 10")); + res.put(kind + "|" + sc.label() + "|writes", "OK"); + } + catch (RuntimeException ex) { + t.line(" release 2 writes " + sc.newConstant() + " : FAILS " + Db.chain(ex)); + res.put(kind + "|" + sc.label() + "|writes", "FAILS " + ex.getClass().getSimpleName()); + t.line(" " + Db.firstLine(Db.root(ex))); + } + } + } + } + } + t.write(); + + for (Db.Kind kind : Db.Kind.values()) { + // ORDINAL: inserting in the middle silently re-labels PAID as CANCELLED, and the old check then refuses SHIPPED + assertThat(res.get(kind + "|ORDINAL, CANCELLED inserted in the middle|reads")).isEqualTo("[NEW, CANCELLED, PAID]"); + assertThat(res.get(kind + "|ORDINAL, CANCELLED inserted in the middle|writes")).isEqualTo("FAILS ConstraintViolationException"); + // ORDINAL appended: old rows fine, the new constant is refused by the generated check + assertThat(res.get(kind + "|ORDINAL, CANCELLED appended|reads")).isEqualTo("[NEW, PAID, SHIPPED]"); + assertThat(res.get(kind + "|ORDINAL, CANCELLED appended|writes")).startsWith("FAILS"); + // ORDINAL renamed: positions do not move, so old rows keep their meaning + assertThat(res.get(kind + "|ORDINAL, PAID renamed PAYMENT_RECEIVED|reads")).isEqualTo("[NEW, PAYMENT_RECEIVED, SHIPPED]"); + // STRING inserted in the middle: names do not move either + assertThat(res.get(kind + "|STRING, CANCELLED inserted in the middle|reads")).isEqualTo("[NEW, PAID, SHIPPED]"); + // STRING appended: old rows fine, new constant refused + assertThat(res.get(kind + "|STRING, CANCELLED appended|reads")).isEqualTo("[NEW, PAID, SHIPPED]"); + assertThat(res.get(kind + "|STRING, CANCELLED appended|writes")).startsWith("FAILS"); + // STRING renamed: reading the old row throws, writing the new name is refused + assertThat(res.get(kind + "|STRING, PAID renamed PAYMENT_RECEIVED|reads")).contains("No enum constant").contains("StatusRen.PAID"); + assertThat(res.get(kind + "|STRING, PAID renamed PAYMENT_RECEIVED|writes")).startsWith("FAILS"); + // stable codes: reads survive the insert and the rename, but the generated check still refuses 'C' + for (String label : List.of("CONVERTER (codes N/P/S), CANCELLED inserted + PAID renamed", + "@EnumeratedValue (codes N/P/S), CANCELLED inserted + PAID renamed")) { + assertThat(res.get(kind + "|" + label + "|reads")).isEqualTo("[NEW, PAYMENT_RECEIVED, SHIPPED]"); + assertThat(res.get(kind + "|" + label + "|writes")).isEqualTo("FAILS ConstraintViolationException"); + } + } + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T03_NativeEnumTest.java b/enums/src/test/java/com/ankurm/enums/T03_NativeEnumTest.java new file mode 100644 index 0000000..862fff7 --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T03_NativeEnumTest.java @@ -0,0 +1,116 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.*; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** PostgreSQL native enum types: what Hibernate creates, how ORDER BY behaves, and what ALTER TYPE can and cannot do. */ +class T03_NativeEnumTest { + + @Test + void nativeEnumOnPostgres() { + Transcript t = new Transcript("03-native-enum", "PostgreSQL native enum (CREATE TYPE ... AS ENUM): ordering, ALTER TYPE, and what cannot be undone"); + t.heading("Ordering. Enum declared as NEW, PAID, SHIPPED, CANCELLED (the order a workflow would use)"); + try (Db db = Db.open(Db.Kind.PG, NatApp.class)) { + t.line("-- type created by Hibernate (hbm2ddl = create)"); + t.line(" enum labels in sort order: " + db.rows("select string_agg(e.enumlabel, ', ' order by e.enumsortorder) from pg_enum e " + + "join pg_type ty on ty.oid = e.enumtypid join pg_namespace n on n.oid = ty.typnamespace " + + "where ty.typname = 'statusapp' and n.nspname = current_schema()")); + db.txv(s -> { + s.persist(new NatApp(1, StatusApp.CANCELLED)); + s.persist(new NatApp(2, StatusApp.SHIPPED)); + s.persist(new NatApp(3, StatusApp.NEW)); + s.persist(new NatApp(4, StatusApp.PAID)); + }); + t.line(" order by status : " + db.rows("select status from orders order by status")); + assertThat(db.rows("select status from orders order by status")).containsExactly("CANCELLED", "NEW", "PAID", "SHIPPED"); + } + try (Db db = Db.open(Db.Kind.PG, "none", Map.of(), NatApp.class)) { + t.line("-- type written by hand, labels in workflow order"); + db.exec("create type statusapp as enum ('NEW', 'PAID', 'SHIPPED', 'CANCELLED')"); + db.exec("create table orders (id bigint primary key, status statusapp)"); + db.txv(s -> { + s.persist(new NatApp(1, StatusApp.CANCELLED)); + s.persist(new NatApp(2, StatusApp.SHIPPED)); + s.persist(new NatApp(3, StatusApp.NEW)); + s.persist(new NatApp(4, StatusApp.PAID)); + }); + t.line(" order by status : " + db.rows("select status from orders order by status")); + assertThat(db.rows("select status from orders order by status")).containsExactly("NEW", "PAID", "SHIPPED", "CANCELLED"); + } + + t.heading("Release 2 needs CANCELLED, but the database type was created from release 1's NEW, PAID, SHIPPED"); + try (Db db1 = Db.open(Db.Kind.PG, NatV1.class)) { + db1.txv(s -> s.persist(new NatV1(1, StatusV1.PAID))); + try (Db db2 = db1.attach("none", Map.of(), NatApp.class)) { + try { + db2.txv(s -> s.persist(new NatApp(10, StatusApp.CANCELLED))); + throw new AssertionError("expected the insert to fail"); + } + catch (RuntimeException ex) { + t.line(" write CANCELLED before ALTER TYPE : " + Db.chain(ex)); + t.line(" " + Db.firstLine(Db.root(ex))); + assertThat(Db.firstLine(Db.root(ex))).contains("invalid input value for enum statusv1"); + } + db1.exec("alter type statusv1 add value 'CANCELLED'"); + db2.txv(s -> s.persist(new NatApp(10, StatusApp.CANCELLED))); + t.line(" after ALTER TYPE statusv1 ADD VALUE 'CANCELLED' : OK, rows " + db2.rows("select id, status from orders order by id")); + t.line(" labels now (appended at the end): " + db1.rows("select string_agg(e.enumlabel, ', ' order by e.enumsortorder) from pg_enum e " + + "join pg_type ty on ty.oid = e.enumtypid join pg_namespace n on n.oid = ty.typnamespace " + + "where ty.typname = 'statusv1' and n.nspname = current_schema()")); + + db1.exec("alter type statusv1 add value 'ON_HOLD' before 'PAID'"); + t.line(" ADD VALUE 'ON_HOLD' BEFORE 'PAID' : labels " + db1.rows("select string_agg(e.enumlabel, ', ' order by e.enumsortorder) from pg_enum e " + + "join pg_type ty on ty.oid = e.enumtypid join pg_namespace n on n.oid = ty.typnamespace " + + "where ty.typname = 'statusv1' and n.nspname = current_schema()")); + + db1.exec("alter type statusv1 rename value 'PAID' to 'PAYMENT_RECEIVED'"); + t.line(" RENAME VALUE 'PAID' TO 'PAYMENT_RECEIVED' : row 1 is now " + db1.rows("select status from orders where id = 1")); + + try { + db1.exec("alter type statusv1 drop value 'ON_HOLD'"); + throw new AssertionError("expected DROP VALUE to be refused"); + } + catch (RuntimeException ex) { + t.line(" ALTER TYPE ... DROP VALUE : " + Db.firstLine(Db.root(ex))); + assertThat(Db.firstLine(Db.root(ex))).contains("dropping an enum value is not implemented"); + } + } + } + + t.heading("ADD VALUE inside a transaction: usable only after commit"); + try (Db db = Db.open(Db.Kind.PG, NatV1.class)) { + try { + db.txv(s -> s.doWork(cn -> { + try (var st = cn.createStatement()) { + st.execute("alter type statusv1 add value 'CANCELLED'"); + st.execute("insert into orders (id, status) values (1, 'CANCELLED')"); + } + })); + t.line(" ADD VALUE then INSERT using it in ONE transaction : OK"); + } + catch (RuntimeException ex) { + t.line(" ADD VALUE then INSERT using it in ONE transaction : " + Db.firstLine(Db.root(ex))); + assertThat(Db.firstLine(Db.root(ex))).contains("unsafe use of new value"); + } + } + t.write(); + } + + @Test + void preferNativeSetting() { + Transcript t = new Transcript("04-prefer-native", "hibernate.type.prefer_native_enum_types on plain @Enumerated(STRING)"); + for (Db.Kind kind : Db.Kind.values()) { + t.heading(kind == Db.Kind.H2 ? "H2" : "PostgreSQL 18"); + for (String v : new String[] {"false", "true"}) { + try (Db db = Db.open(kind, "create-drop", Map.of("hibernate.type.prefer_native_enum_types", v), StrV1.class)) { + t.line("-- prefer_native_enum_types=" + v); + t.lines(db.describeStatus(), " "); + } + } + } + t.write(); + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T04_UpdateTest.java b/enums/src/test/java/com/ankurm/enums/T04_UpdateTest.java new file mode 100644 index 0000000..fea475f --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T04_UpdateTest.java @@ -0,0 +1,43 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.*; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Does hibernate.hbm2ddl.auto=update fix the schema after you add a constant? And what is the manual fix per mapping? */ +class T04_UpdateTest { + + @Test + void hbm2ddlUpdateAfterAddingAConstant() { + Transcript t = new Transcript("05-hbm2ddl-update", "Adding CANCELLED, then starting release 2 with hbm2ddl=update: is the schema fixed?"); + for (Db.Kind kind : Db.Kind.values()) { + t.heading(kind == Db.Kind.H2 ? "H2" : "PostgreSQL 18"); + check(t, kind, "ORDINAL", OrdV1.class, OrdApp.class, (id) -> new OrdApp(id, StatusApp.CANCELLED), "alter table orders drop constraint "); + check(t, kind, "STRING", StrV1.class, StrApp.class, (id) -> new StrApp(id, StatusApp.CANCELLED), null); + if (kind == Db.Kind.PG) { + check(t, kind, "NAMED_ENUM", NatV1.class, NatApp.class, (id) -> new NatApp(id, StatusApp.CANCELLED), null); + } + } + t.write(); + } + + private void check(Transcript t, Db.Kind kind, String label, Class r1, Class r2, + java.util.function.LongFunction make, String unused) { + try (Db db1 = Db.open(kind, r1)) { + try (Db db2 = db1.attach("update", Map.of(), r2)) { + t.line("-- " + label); + t.lines(db2.describeStatus(), " after update: "); + try { + db2.txv(s -> s.persist(make.apply(10))); + t.line(" write CANCELLED : OK, stored " + db2.rows("select status from orders where id = 10")); + throw new AssertionError(label + ": hbm2ddl=update unexpectedly fixed the schema"); + } + catch (RuntimeException ex) { + t.line(" write CANCELLED : FAILS " + Db.firstLine(Db.root(ex))); + } + } + } + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T05_FixTest.java b/enums/src/test/java/com/ankurm/enums/T05_FixTest.java new file mode 100644 index 0000000..8228eed --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T05_FixTest.java @@ -0,0 +1,91 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** The hand-written migration each change needs on PostgreSQL, run for real, with release 2's reads and writes afterwards. */ +class T05_FixTest { + + private static List read(Db db, String entity) { + List names = new ArrayList<>(); + db.tx(s -> s.createSelectionQuery("from " + entity + " o order by o.id", Row.class).getResultList()) + .forEach(r -> names.add(r.statusName())); + return names; + } + + @Test + void migrations() { + Transcript t = new Transcript("06-migrations", "The migration each enum change needs (PostgreSQL 18), and release 2 afterwards"); + + t.heading("ORDINAL: insert CANCELLED between NEW and PAID"); + try (Db db1 = Db.open(Db.Kind.PG, OrdV1.class)) { + db1.txv(s -> { + s.persist(new OrdV1(1, StatusV1.NEW)); + s.persist(new OrdV1(2, StatusV1.PAID)); + s.persist(new OrdV1(3, StatusV1.SHIPPED)); + }); + try (Db db2 = db1.attach("none", Map.of(), OrdMid.class)) { + db1.exec("alter table orders drop constraint orders_status_check"); + db1.exec("update orders set status = status + 1 where status >= 1"); + db1.exec("alter table orders add constraint orders_status_check check (status between 0 and 3)"); + t.line(" migration : drop check; UPDATE orders SET status = status + 1 WHERE status >= 1; add check (status between 0 and 3)"); + t.line(" stored : " + db1.rows("select id, status from orders order by id")); + List names = read(db2, "OrdMid"); + t.line(" release 2 reads : " + names); + assertThat(names).containsExactly("NEW", "PAID", "SHIPPED"); + db2.txv(s -> s.persist(new OrdMid(10, StatusMid.CANCELLED))); + t.line(" release 2 writes CANCELLED : OK, stored " + db2.rows("select status from orders where id = 10")); + } + } + + t.heading("STRING: append CANCELLED"); + try (Db db1 = Db.open(Db.Kind.PG, StrV1.class)) { + db1.txv(s -> s.persist(new StrV1(1, StatusV1.PAID))); + try (Db db2 = db1.attach("none", Map.of(), StrApp.class)) { + db1.exec("alter table orders drop constraint orders_status_check"); + db1.exec("alter table orders add constraint orders_status_check check (status in ('NEW', 'PAID', 'SHIPPED', 'CANCELLED'))"); + t.line(" migration : drop check; add check (status in ('NEW', 'PAID', 'SHIPPED', 'CANCELLED'))"); + db2.txv(s -> s.persist(new StrApp(10, StatusApp.CANCELLED))); + t.line(" release 2 writes CANCELLED : OK, rows " + db2.rows("select id, status from orders order by id")); + } + } + + t.heading("STRING: rename PAID to PAYMENT_RECEIVED"); + try (Db db1 = Db.open(Db.Kind.PG, StrV1.class)) { + db1.txv(s -> { + s.persist(new StrV1(1, StatusV1.NEW)); + s.persist(new StrV1(2, StatusV1.PAID)); + }); + try (Db db2 = db1.attach("none", Map.of(), StrRen.class)) { + db1.exec("alter table orders drop constraint orders_status_check"); + db1.exec("update orders set status = 'PAYMENT_RECEIVED' where status = 'PAID'"); + db1.exec("alter table orders add constraint orders_status_check check (status in ('NEW', 'PAYMENT_RECEIVED', 'SHIPPED'))"); + t.line(" migration : drop check; UPDATE ... SET status = 'PAYMENT_RECEIVED' WHERE status = 'PAID'; add check"); + List names = read(db2, "StrRen"); + t.line(" release 2 reads : " + names); + assertThat(names).containsExactly("NEW", "PAYMENT_RECEIVED"); + } + } + + t.heading("CONVERTER or @EnumeratedValue: insert CANCELLED and rename PAID (codes unchanged)"); + try (Db db1 = Db.open(Db.Kind.PG, ConvV1.class)) { + db1.txv(s -> s.persist(new ConvV1(1, CodedV1.PAID))); + try (Db db2 = db1.attach("none", Map.of(), ConvMid.class)) { + db1.exec("alter table orders drop constraint orders_status_check"); + db1.exec("alter table orders add constraint orders_status_check check (status in ('N', 'C', 'P', 'S'))"); + t.line(" migration : drop check; add check (status in ('N', 'C', 'P', 'S')); no UPDATE, no data touched"); + List names = read(db2, "ConvMid"); + t.line(" release 2 reads : " + names); + assertThat(names).containsExactly("PAYMENT_RECEIVED"); + db2.txv(s -> s.persist(new ConvMid(10, CodedMid.CANCELLED))); + t.line(" release 2 writes CANCELLED : OK, stored " + db2.rows("select status from orders where id = 10")); + } + } + t.write(); + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T06_QueryTest.java b/enums/src/test/java/com/ankurm/enums/T06_QueryTest.java new file mode 100644 index 0000000..ed83d30 --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T06_QueryTest.java @@ -0,0 +1,122 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.*; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** HQL against enums: the SQL each mapping sends, how ORDER BY sorts, and what a bad value in the column does. */ +class T06_QueryTest { + + @Test + void hqlAndOrdering() { + Transcript t = new Transcript("07-queries", "HQL on enum attributes: SQL sent, ORDER BY, and a bad value in the column (PostgreSQL 18)"); + + t.heading("The SQL Hibernate sends for from X o where o.status = :s (parameter = PAID / PAYMENT_RECEIVED)"); + try (Db db = Db.open(Db.Kind.PG, OrdV1.class)) { + db.txv(s -> s.persist(new OrdV1(1, StatusV1.PAID))); + List sql = Db.sql(() -> db.tx(s -> s.createSelectionQuery("from OrdV1 o where o.status = :s", OrdV1.class) + .setParameter("s", StatusV1.PAID).getResultList())); + t.step("ORDINAL", sql); + assertThat(sql).hasSize(1); + } + try (Db db = Db.open(Db.Kind.PG, StrV1.class)) { + db.txv(s -> s.persist(new StrV1(1, StatusV1.PAID))); + t.step("STRING", Db.sql(() -> db.tx(s -> s.createSelectionQuery("from StrV1 o where o.status = :s", StrV1.class) + .setParameter("s", StatusV1.PAID).getResultList()))); + } + try (Db db = Db.open(Db.Kind.PG, NatV1.class)) { + db.txv(s -> s.persist(new NatV1(1, StatusV1.PAID))); + t.step("NAMED_ENUM", Db.sql(() -> db.tx(s -> s.createSelectionQuery("from NatV1 o where o.status = :s", NatV1.class) + .setParameter("s", StatusV1.PAID).getResultList()))); + } + try (Db db = Db.open(Db.Kind.PG, ConvV1.class)) { + db.txv(s -> s.persist(new ConvV1(1, CodedV1.PAID))); + List sql = Db.sql(() -> db.tx(s -> s.createSelectionQuery("from ConvV1 o where o.status = :s", ConvV1.class) + .setParameter("s", CodedV1.PAID).getResultList())); + t.step("CONVERTER", sql); + } + try (Db db = Db.open(Db.Kind.PG, ConvV1.class)) { + db.txv(s -> s.persist(new ConvV1(1, CodedV1.PAID))); + t.step("CONVERTER, enum literal in the HQL text", Db.sql(() -> db.tx(s -> s.createSelectionQuery( + "from ConvV1 o where o.status = com.ankurm.enums.Variants.CodedV1.PAID", ConvV1.class).getResultList()))); + } + + t.heading("ORDER BY status on NEW, SHIPPED, CANCELLED, PAID stored under each mapping"); + try (Db db = Db.open(Db.Kind.PG, OrdApp.class)) { + db.txv(s -> { + s.persist(new OrdApp(1, StatusApp.NEW)); + s.persist(new OrdApp(2, StatusApp.SHIPPED)); + s.persist(new OrdApp(3, StatusApp.CANCELLED)); + s.persist(new OrdApp(4, StatusApp.PAID)); + }); + List r = db.tx(s -> s.createSelectionQuery("select o.status from OrdApp o order by o.status", StatusApp.class).getResultList()) + .stream().map(Enum::name).toList(); + t.line(" ORDINAL (enum NEW, PAID, SHIPPED, CANCELLED) : " + r); + assertThat(r).containsExactly("NEW", "PAID", "SHIPPED", "CANCELLED"); + } + try (Db db = Db.open(Db.Kind.PG, StrApp.class)) { + db.txv(s -> { + s.persist(new StrApp(1, StatusApp.NEW)); + s.persist(new StrApp(2, StatusApp.SHIPPED)); + s.persist(new StrApp(3, StatusApp.CANCELLED)); + s.persist(new StrApp(4, StatusApp.PAID)); + }); + List r = db.tx(s -> s.createSelectionQuery("select o.status from StrApp o order by o.status", StatusApp.class).getResultList()) + .stream().map(Enum::name).toList(); + t.line(" STRING : " + r); + assertThat(r).containsExactly("CANCELLED", "NEW", "PAID", "SHIPPED"); + } + try (Db db = Db.open(Db.Kind.PG, ConvMid.class)) { + db.txv(s -> { + s.persist(new ConvMid(1, CodedMid.NEW)); + s.persist(new ConvMid(2, CodedMid.SHIPPED)); + s.persist(new ConvMid(3, CodedMid.CANCELLED)); + s.persist(new ConvMid(4, CodedMid.PAYMENT_RECEIVED)); + }); + List r = db.rows("select status from orders order by status"); + t.line(" CONVERTER (codes C, N, P, S, stored values) : " + r); + assertThat(r).containsExactly("C", "N", "P", "S"); + } + + t.heading("A value the enum does not know, in the column"); + try (Db db = Db.open(Db.Kind.PG, ConvV1.class)) { + db.txv(s -> s.persist(new ConvV1(1, CodedV1.PAID))); + try { + db.exec("insert into orders (id, status) values (2, 'X')"); + throw new AssertionError("expected the check constraint to refuse 'X'"); + } + catch (RuntimeException ex) { + t.line(" insert 'X' with Hibernate's generated check in place : " + Db.firstLine(Db.root(ex))); + } + db.exec("alter table orders drop constraint orders_status_check"); + db.exec("insert into orders (id, status) values (2, 'X')"); + try { + db.tx(s -> s.createSelectionQuery("from ConvV1 o order by o.id", ConvV1.class).getResultList()); + throw new AssertionError("expected the converter to throw"); + } + catch (RuntimeException ex) { + t.line(" read after the check is dropped and 'X' is inserted : " + Db.chain(ex)); + t.line(" " + Db.firstLine(Db.root(ex))); + assertThat(Db.firstLine(Db.root(ex))).contains("Unknown CodedV1 code 'X'"); + } + } + try (Db db = Db.open(Db.Kind.PG, OrdV1.class)) { + db.txv(s -> s.persist(new OrdV1(1, StatusV1.PAID))); + db.exec("alter table orders drop constraint orders_status_check"); + db.exec("insert into orders (id, status) values (2, 7)"); + try { + db.tx(s -> s.createSelectionQuery("from OrdV1 o order by o.id", OrdV1.class).getResultList()); + throw new AssertionError("expected the read to fail"); + } + catch (RuntimeException ex) { + t.line(" ORDINAL with the check dropped and ordinal 7 stored : " + Db.chain(ex)); + t.line(" " + Db.firstLine(Db.root(ex))); + assertThat(Db.root(ex)).isInstanceOf(ArrayIndexOutOfBoundsException.class); + } + } + t.write(); + } +} diff --git a/enums/src/test/java/com/ankurm/enums/T07_PreferNativeAssertTest.java b/enums/src/test/java/com/ankurm/enums/T07_PreferNativeAssertTest.java new file mode 100644 index 0000000..f0329ae --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/T07_PreferNativeAssertTest.java @@ -0,0 +1,21 @@ +package com.ankurm.enums; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.enums.Variants.StrV1; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** hibernate.type.prefer_native_enum_types=true turns plain STRING into a native enum type on PostgreSQL. */ +class T07_PreferNativeAssertTest { + + @Test + void preferNativeEnumTypesOnPostgres() { + try (Db db = Db.open(Db.Kind.PG, "create-drop", Map.of("hibernate.type.prefer_native_enum_types", "true"), StrV1.class)) { + assertThat(db.describeStatus()).containsExactly("column type: statusv1"); + } + try (Db db = Db.open(Db.Kind.PG, "create-drop", Map.of("hibernate.type.prefer_native_enum_types", "false"), StrV1.class)) { + assertThat(db.describeStatus()).anyMatch(x -> x.equals("column type: character varying(255)")); + } + } +} diff --git a/enums/src/test/java/com/ankurm/enums/Transcript.java b/enums/src/test/java/com/ankurm/enums/Transcript.java new file mode 100644 index 0000000..c83fadc --- /dev/null +++ b/enums/src/test/java/com/ankurm/enums/Transcript.java @@ -0,0 +1,61 @@ +package com.ankurm.enums; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Collects what a test observed and writes output/NN-name.txt; the tests assert the same facts. */ +final class Transcript { + + static final String VERSION = System.getProperty("h.version", "?"); + + private final List lines = new ArrayList<>(); + private final Path file; + + Transcript(String name, String title) { + this.file = Path.of("output", name + ".txt"); + line("# " + title); + line("# Hibernate ORM " + VERSION + ", H2 2.4.240 and PostgreSQL 18.6, JDK " + Runtime.version().feature()); + } + + Transcript line(String s) { + lines.add(s); + return this; + } + + Transcript heading(String s) { + line(""); + return line("== " + s); + } + + Transcript lines(List ls, String prefix) { + for (String s : ls) { + line(prefix + s); + } + return this; + } + + /** A step: the label, then every SQL statement Hibernate prepared during it. */ + Transcript step(String label, List sql) { + line("-- " + label); + if (sql.isEmpty()) { + line(" (no SQL)"); + } + for (String s : sql) { + line(" sql> " + s); + } + return this; + } + + void write() { + try { + Files.createDirectories(file.getParent()); + Files.write(file, lines); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + } +}