Add enums module: enum mapping in Hibernate 7.4.17.Final (ORDINAL trap, STRING, PostgreSQL native enum, AttributeConverter, @EnumeratedValue), what release 2 reads and writes after a constant is inserted, appended or renamed, hbm2ddl=update limits, migrations (H2 2.4.240, PostgreSQL 18.6)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5y3ArhRbakfu1ELsP
This commit is contained in:
@@ -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<CodedV1, String> {
|
||||
@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<CodedMid, String> {
|
||||
@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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String, String> 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<String, String> 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<String, String> 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> T tx(Function<Session, T> 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<Session> work) {
|
||||
tx(s -> {
|
||||
work.accept(s);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs the action and returns the SQL Hibernate prepared while it ran. */
|
||||
static List<String> 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<String> rows(String sql) {
|
||||
return tx(s -> s.doReturningWork(cn -> {
|
||||
List<String> 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<String> describeStatus() {
|
||||
List<String> 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Mapping> 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<Enum,String>)", 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<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<Long, String, Row> make1, Class<?> r2, String entity2,
|
||||
BiFunction<Long, String, Row> make2, String newConstant, String change) {
|
||||
}
|
||||
|
||||
static final List<Scenario> 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<String, String> 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<String> 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<Variants.Row> 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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> read(Db db, String entity) {
|
||||
List<String> 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<String> 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<String> 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<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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<String> 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<String> 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<String> 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();
|
||||
}
|
||||
}
|
||||
@@ -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)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user