diff --git a/README.md b/README.md index 828e3d4..0ca97fa 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Companion code for a series of posts on [ankurm.com](https://ankurm.com) coverin | [`jpa-auditing/`](./jpa-auditing) | JPA Auditing in Spring Boot 4: @CreatedDate, @LastModifiedBy and the Current User | Spring Data JPA 4.1.2, Spring Security 7.1.2, Hibernate 7.4.13.Final (+ Envers), H2 2.4.240 | | [`jdbcclient/`](./jdbcclient) | JdbcClient in Spring Framework 7: Modern JDBC Without JPA (vs JdbcTemplate) | Spring Framework 7.0.10, Spring Boot 4.1.2, HikariCP 7.0.2, H2 2.4.240 | | [`mybatis/`](./mybatis) | MyBatis with Spring Boot 4: Mappers, Dynamic SQL and Pagination | MyBatis 3.5.19 (starter 4.1.0), PageHelper 6.1.1, Spring Boot 4.2.0, H2 2.5.252 | +| [`jooq/`](./jooq) | jOOQ with Spring Boot 4: Type-Safe SQL, Code Generation and Testcontainers | jOOQ 3.21.9, Flyway 12.11.0, Spring Boot 4.2.0, PostgreSQL 17 (Testcontainers 2.0.5) | Each module has its own `pom.xml`, a `docker-compose.yml` for its backing services, and a `docs/output/` directory holding the real, re-runnable transcripts that every number quoted in its post traces back to. There are no narrative doc chapters here — the deeper material for each post lives in accordions inside the post itself. diff --git a/jooq/README.md b/jooq/README.md new file mode 100644 index 0000000..b58a78e --- /dev/null +++ b/jooq/README.md @@ -0,0 +1,51 @@ +# jooq + +Companion module for the ankurm.com post **jOOQ with Spring Boot 4: Type-Safe SQL, Code Generation and Testcontainers**. + +| Piece | Version | +|---|---| +| Spring Boot | 4.2.0 | +| jOOQ (managed by the Boot BOM) | 3.21.9 (3.21.10 is on Maven Central; Boot 4.2.0 does not manage it yet) | +| Flyway (managed) | 12.11.0 | +| PostgreSQL | 17 (`postgres:17-alpine`, 17.12) via Testcontainers 2.0.5 | +| JDK | Temurin 25.0.5.1 | + +## What is here + +``` +src/main/resources/db/migration/ V1 (schema) and V2 (isbn column): the single source of truth +src/main/java/.../generated/ jOOQ output, committed, regenerated by scripts/codegen.sh +src/main/java/.../BookshopRepository.java typed queries: RETURNING, dynamic WHERE, MULTISET, CTE + window, upsert, seek +src/main/java/.../StockService.java transaction behaviour under Spring +src/broken/ sources that must NOT compile; driven by scripts/compile-errors.sh +src/test/java/ tests that write output/*.txt and assert the same facts +``` + +## Run it + +```bash +export JAVA_HOME= +scripts/run-all.sh # needs Docker; regenerates every file in output/ +mvn test # just the tests (starts PostgreSQL 17 in Testcontainers) +scripts/codegen.sh # throwaway PostgreSQL -> Flyway -> jOOQ codegen -> src/main/java +``` + +## Output index + +| File | Shows | Written by | +|---|---|---| +| `output/00-codegen-run.txt` | the generator run and a before/after checksum | `scripts/codegen.sh` via `run-all.sh` | +| `output/01-codegen-drift-check.txt` | committed generated code equals a fresh generation | `CodegenDriftTest` | +| `output/02-autoconfig-and-insert-returning.txt` | dialect, listeners, `INSERT ... RETURNING`, identity column | `QueryTests` | +| `output/03-dynamic-where.txt` | one method, three filter sets, three SQL statements | `QueryTests` | +| `output/04-multiset.txt` | parent + children in one statement | `QueryTests` | +| `output/05-cte-window.txt` | CTE + `rank()`, aggregate leaderboard | `QueryTests` | +| `output/06-upsert-and-keyset.txt` | `ON CONFLICT DO UPDATE`, `seek()` | `QueryTests` | +| `output/07-runtime-failure-of-plain-sql.txt` | a string-SQL typo fails at runtime | `QueryTests` | +| `output/08-transactions.txt` | six transaction scenarios | `TransactionTests` | +| `output/09-container-lifecycle-trap.txt` | per-class `@Container` + cached Spring context | `scripts/container-trap.sh` | +| `output/10-compile-errors.txt` | what javac says for a wrong type, a typo, a dropped column | `scripts/compile-errors.sh` | +| `output/11-drift-detected.txt` | the drift test failing after an unregenerated migration | `scripts/drift-demo.sh` | +| `output/12-jooqtest-slice.txt` | what `@JooqTest` does and does not load | `JooqSliceTest` | +| `output/13-startup-log-lines.txt` | jOOQ banner and the PostgreSQL dialect WARN | `scripts/startup-warnings.sh` | +| `output/14-missing-flyway-database-module.txt` | Flyway 12 without `flyway-database-postgresql` | `scripts/missing-flyway-module.sh` | diff --git a/jooq/output/00-codegen-run.txt b/jooq/output/00-codegen-run.txt new file mode 100644 index 0000000..dc284fe --- /dev/null +++ b/jooq/output/00-codegen-run.txt @@ -0,0 +1,20 @@ +$ scripts/codegen.sh +generated files: +src/main/java/com/ankurm/jooq/generated/DefaultCatalog.java +src/main/java/com/ankurm/jooq/generated/Indexes.java +src/main/java/com/ankurm/jooq/generated/Keys.java +src/main/java/com/ankurm/jooq/generated/Public.java +src/main/java/com/ankurm/jooq/generated/Tables.java +src/main/java/com/ankurm/jooq/generated/enums/Genre.java +src/main/java/com/ankurm/jooq/generated/tables/Author.java +src/main/java/com/ankurm/jooq/generated/tables/Book.java +src/main/java/com/ankurm/jooq/generated/tables/Review.java +src/main/java/com/ankurm/jooq/generated/tables/pojos/Author.java +src/main/java/com/ankurm/jooq/generated/tables/pojos/Book.java +src/main/java/com/ankurm/jooq/generated/tables/pojos/Review.java +src/main/java/com/ankurm/jooq/generated/tables/records/AuthorRecord.java +src/main/java/com/ankurm/jooq/generated/tables/records/BookRecord.java +src/main/java/com/ankurm/jooq/generated/tables/records/ReviewRecord.java + +checksum of generated sources before: 2b5f174e286873e9 +checksum of generated sources after: 2b5f174e286873e9 diff --git a/jooq/output/01-codegen-drift-check.txt b/jooq/output/01-codegen-drift-check.txt new file mode 100644 index 0000000..541d640 --- /dev/null +++ b/jooq/output/01-codegen-drift-check.txt @@ -0,0 +1,4 @@ +files regenerated from the live schema: 15 +files committed in src/main/java: 15 +byte-identical files: 15 +verdict: committed generated code matches Flyway V1 + V2 diff --git a/jooq/output/02-autoconfig-and-insert-returning.txt b/jooq/output/02-autoconfig-and-insert-returning.txt new file mode 100644 index 0000000..3958f8d --- /dev/null +++ b/jooq/output/02-autoconfig-and-insert-returning.txt @@ -0,0 +1,10 @@ +DSLContext dialect: POSTGRES +Flyway history: [1 bookshop success=true, 2 book isbn success=true] +listener providers on the DSLContext: 2 +transaction provider: org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider +plain ExecuteListener bean calls so far: 0 (bean exists: true) + +SQL: insert into "public"."book" ("author_id", "title", "genre", "price", "published_on", "stock", "isbn") values (?, ?, cast(? as "public"."genre"), ?, cast(? as date), ?, ?) returning "public"."book"."id", "public"."book"."author_id", "public"."book"."title", "public"."book"."genre", "public"."book"."price", "public"."book"."published_on", "public"."book"."stock", "public"."book"."isbn" +Returned POJO (a generated Java record): Book (7, 1, Returning Demo, TECH, 10.50, 2026-02-02, 1, 978-9-99) + +insert with explicit id on GENERATED ALWAYS column: ERROR: cannot insert a non-DEFAULT value into column "id" diff --git a/jooq/output/03-dynamic-where.txt b/jooq/output/03-dynamic-where.txt new file mode 100644 index 0000000..44d370e --- /dev/null +++ b/jooq/output/03-dynamic-where.txt @@ -0,0 +1,15 @@ +SQL: select "public"."book"."title", "public"."author"."name", "public"."book"."genre", "public"."book"."price" from "public"."book" join "public"."author" on "public"."author"."id" = "public"."book"."author_id" order by "public"."book"."title" + row: BookRow[title=Compilers for Humans, author=Grace Hopper, genre=TECH, price=45.00] + row: BookRow[title=Debugging a Moth, author=Grace Hopper, genre=HISTORY, price=18.75] + row: BookRow[title=Kata of Clean Code, author=Kenji Tanaka, genre=TECH, price=39.90] + row: BookRow[title=Notes on the Analytical Engine, author=Ada Lovelace, genre=SCIENCE, price=24.50] + row: BookRow[title=Poetical Science, author=Ada Lovelace, genre=FICTION, price=12.00] + row: BookRow[title=Tokyo Trains, author=Kenji Tanaka, genre=HISTORY, price=22.00] + +SQL: select "public"."book"."title", "public"."author"."name", "public"."book"."genre", "public"."book"."price" from "public"."book" join "public"."author" on "public"."author"."id" = "public"."book"."author_id" where "public"."book"."genre" = cast(? as "public"."genre") order by "public"."book"."title" + row: BookRow[title=Compilers for Humans, author=Grace Hopper, genre=TECH, price=45.00] + row: BookRow[title=Kata of Clean Code, author=Kenji Tanaka, genre=TECH, price=39.90] + +SQL: select "public"."book"."title", "public"."author"."name", "public"."book"."genre", "public"."book"."price" from "public"."book" join "public"."author" on "public"."author"."id" = "public"."book"."author_id" where (lower("public"."book"."title") like ('%' || replace(replace(replace(lower(?), '!', '!!'), '%', '!%'), '_', '!_') || '%') escape '!' and "public"."book"."genre" = cast(? as "public"."genre") and "public"."book"."price" <= ? and "public"."author"."country" = ?) order by "public"."book"."title" + row: BookRow[title=Kata of Clean Code, author=Kenji Tanaka, genre=TECH, price=39.90] + diff --git a/jooq/output/04-multiset.txt b/jooq/output/04-multiset.txt new file mode 100644 index 0000000..09525ef --- /dev/null +++ b/jooq/output/04-multiset.txt @@ -0,0 +1,11 @@ +statements sent: 1 +SQL: select "public"."book"."title", (select coalesce(jsonb_agg(jsonb_build_array(t."v0", t."v1")), jsonb_build_array()) from (select "public"."review"."rating" as "v0", "public"."review"."body" as "v1" from "public"."review" where "public"."review"."book_id" = "public"."book"."id" order by "public"."review"."id") as t) from "public"."book" order by "public"."book"."title" + +BookWithReviews[title=Compilers for Humans, reviews=[ReviewView[rating=5, body=Changed how I think], ReviewView[rating=4, body=Great examples], ReviewView[rating=5, body=Buy it]]] +BookWithReviews[title=Debugging a Moth, reviews=[]] +BookWithReviews[title=Kata of Clean Code, reviews=[ReviewView[rating=2, body=Too many koans]]] +BookWithReviews[title=Notes on the Analytical Engine, reviews=[ReviewView[rating=5, body=Foundational], ReviewView[rating=4, body=Dense but worth it]]] +BookWithReviews[title=Poetical Science, reviews=[ReviewView[rating=3, body=Charming]]] +BookWithReviews[title=Tokyo Trains, reviews=[ReviewView[rating=4, body=Lovely photographs]]] + +flat LEFT JOIN returns 9 rows for 6 books; MULTISET returns 6 rows diff --git a/jooq/output/05-cte-window.txt b/jooq/output/05-cte-window.txt new file mode 100644 index 0000000..d64e875 --- /dev/null +++ b/jooq/output/05-cte-window.txt @@ -0,0 +1,11 @@ +SQL: with "ratings" as (select "public"."book"."genre", "public"."book"."title", avg(cast("public"."review"."rating" as double precision)) as "avg_rating" from "public"."book" join "public"."review" on "public"."review"."book_id" = "public"."book"."id" group by "public"."book"."genre", "public"."book"."title"), "ranked" as (select "ratings"."genre", "ratings"."title", "ratings"."avg_rating", rank() over (partition by "ratings"."genre" order by "ratings"."avg_rating" desc, "ratings"."title") as "rnk" from "ratings") select "ranked"."genre", "ranked"."title", "ranked"."avg_rating", "ranked"."rnk" from "ranked" where "ranked"."rnk" = ? order by "ranked"."genre" + +GenreLeader[genre=FICTION, title=Poetical Science, avgRating=3.0, rank=1] +GenreLeader[genre=SCIENCE, title=Notes on the Analytical Engine, avgRating=4.5, rank=1] +GenreLeader[genre=HISTORY, title=Tokyo Trains, avgRating=4.0, rank=1] +GenreLeader[genre=TECH, title=Compilers for Humans, avgRating=4.666666666666667, rank=1] + +SQL: select "public"."author"."name", count(*), sum(("public"."book"."price" * "public"."book"."stock")) from "public"."author" join "public"."book" on "public"."book"."author_id" = "public"."author"."id" group by "public"."author"."name" order by sum(("public"."book"."price" * "public"."book"."stock")) desc +LeaderboardRow[author=Kenji Tanaka, books=2, catalogueValue=544.80] +LeaderboardRow[author=Grace Hopper, books=2, catalogueValue=315.00] +LeaderboardRow[author=Ada Lovelace, books=2, catalogueValue=305.00] diff --git a/jooq/output/06-upsert-and-keyset.txt b/jooq/output/06-upsert-and-keyset.txt new file mode 100644 index 0000000..2e03742 --- /dev/null +++ b/jooq/output/06-upsert-and-keyset.txt @@ -0,0 +1,8 @@ +SQL: insert into "public"."book" ("author_id", "title", "genre", "price", "published_on", "stock", "isbn") values (?, ?, cast(? as "public"."genre"), ?, cast(? as date), ?, ?) on conflict ("isbn") do update set "stock" = ("public"."book"."stock" + ?) returning "public"."book"."id", "public"."book"."author_id", "public"."book"."title", "public"."book"."genre", "public"."book"."price", "public"."book"."published_on", "public"."book"."stock", "public"."book"."isbn" +first call -> stock 4 (inserted) +second call -> stock 8 (conflict, stock added); same id: true + +page 1 SQL: select "public"."book"."id" from "public"."book" where "public"."book"."id" > ? order by "public"."book"."id" fetch next ? rows only +page 1: [1, 2, 3] next=3 +page 2 SQL: select "public"."book"."id" from "public"."book" where "public"."book"."id" > ? order by "public"."book"."id" fetch next ? rows only +page 2: [4, 5, 6] next=6 diff --git a/jooq/output/07-runtime-failure-of-plain-sql.txt b/jooq/output/07-runtime-failure-of-plain-sql.txt new file mode 100644 index 0000000..c5ed534 --- /dev/null +++ b/jooq/output/07-runtime-failure-of-plain-sql.txt @@ -0,0 +1,3 @@ +dsl.fetch("select isbnn from book") compiles fine and fails at runtime: + exception type: org.springframework.jdbc.BadSqlGrammarException + root cause: ERROR: column "isbnn" does not exist diff --git a/jooq/output/08-transactions.txt b/jooq/output/08-transactions.txt new file mode 100644 index 0000000..7ec02e2 --- /dev/null +++ b/jooq/output/08-transactions.txt @@ -0,0 +1,8 @@ +seeded authors: 3 +1. no @Transactional, exception after 2 inserts -> author persisted: true, book persisted: true +2. @Transactional, RuntimeException -> author persisted: false, book persisted: false +3. @Transactional, checked IOException -> author persisted: true, book persisted: true +4. @Transactional(rollbackFor=Exception.class) -> author persisted: false, book persisted: false +5. dsl.transaction inside @Transactional, inner fails, caught -> caught inner failure, outer continues (author id 8) + outer author persisted: true, inner author persisted: false +6. dsl.transaction alone: success persisted: true; failure persisted: false diff --git a/jooq/output/09-container-lifecycle-trap.txt b/jooq/output/09-container-lifecycle-trap.txt new file mode 100644 index 0000000..6c804cf --- /dev/null +++ b/jooq/output/09-container-lifecycle-trap.txt @@ -0,0 +1,8 @@ +per-class @Container, two test classes sharing one cached Spring context (hikari connection-timeout shortened to 2 s) +5 Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 2000ms (total=0, active=0, idle=0, waiting=0) +1 Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 2001ms (total=0, active=0, idle=0, waiting=0) +10 WARN 4798 --- [jooq-demo] [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@HASH (This connection has been closed.). Possibly consider using a shorter maxLifetime value +1 [ERROR] Tests run: 6, Failures: 0, Errors: 6, Skipped: 0, Time elapsed: 20.43 s <<< FAILURE! -- in com.ankurm.jooq.QueryTests +1 [ERROR] Tests run: 7, Failures: 0, Errors: 6, Skipped: 0 +5 org.springframework.dao.TransientDataAccessResourceException: jOOQ; SQL [TRUNCATE review, book, author RESTART IDENTITY CASCADE]; HikariPool-1 - Connection is not available, request timed out after 2000ms (total=0, active=0, idle=0, waiting=0) +1 org.springframework.dao.TransientDataAccessResourceException: jOOQ; SQL [TRUNCATE review, book, author RESTART IDENTITY CASCADE]; HikariPool-1 - Connection is not available, request timed out after 2001ms (total=0, active=0, idle=0, waiting=0) diff --git a/jooq/output/10-compile-errors.txt b/jooq/output/10-compile-errors.txt new file mode 100644 index 0000000..0b4ffbb --- /dev/null +++ b/jooq/output/10-compile-errors.txt @@ -0,0 +1,26 @@ +== A. wrong type: BOOK.PRICE.eq("12.50") == +src/main/java/com/ankurm/jooq/WrongType.java:[10,53] no suitable method found for eq(java.lang.String) + method org.jooq.Field.eq(java.math.BigDecimal) is not applicable + (argument mismatch; java.lang.String cannot be converted to java.math.BigDecimal) + method org.jooq.Field.eq(org.jooq.Select>) is not applicable + (argument mismatch; java.lang.String cannot be converted to org.jooq.Select>) + method org.jooq.Field.eq(org.jooq.Field) is not applicable + (argument mismatch; java.lang.String cannot be converted to org.jooq.Field) + method org.jooq.Field.eq(org.jooq.QuantifiedSelect>) is not applicable + (argument mismatch; java.lang.String cannot be converted to org.jooq.QuantifiedSelect>) + +== B. typo: BOOK.ISBNN == +src/main/java/com/ankurm/jooq/Typo.java:[10,31] cannot find symbol + symbol: variable ISBNN + location: variable BOOK of type com.ankurm.jooq.generated.tables.Book + +== C. regenerate from schema version 1 only (no isbn column), compile the unchanged application == +src/main/java/com/ankurm/jooq/BookshopRepository.java:[49,26] cannot find symbol + symbol: variable ISBN + location: variable BOOK of type com.ankurm.jooq.generated.tables.Book +src/main/java/com/ankurm/jooq/BookshopRepository.java:[131,33] cannot find symbol + symbol: variable ISBN + location: variable BOOK of type com.ankurm.jooq.generated.tables.Book +src/main/java/com/ankurm/jooq/BookshopRepository.java:[130,26] cannot find symbol + symbol: variable ISBN + location: variable BOOK of type com.ankurm.jooq.generated.tables.Book diff --git a/jooq/output/11-drift-detected.txt b/jooq/output/11-drift-detected.txt new file mode 100644 index 0000000..274394e --- /dev/null +++ b/jooq/output/11-drift-detected.txt @@ -0,0 +1,5 @@ +added src/main/resources/db/migration/V3__book_subtitle.sql, did NOT regenerate +[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 26.50 s <<< FAILURE! -- in com.ankurm.jooq.CodegenDriftTest +org.opentest4j.AssertionFailedError: generated code is stale, run scripts/codegen.sh. Differing files: [tables/Book.java, tables/pojos/Book.java, tables/records/BookRecord.java] ==> expected: but was: +[ERROR] CodegenDriftTest.committedGeneratedCodeMatchesMigrations:64 generated code is stale, run scripts/codegen.sh. Differing files: [tables/Book.java, tables/pojos/Book.java, tables/records/BookRecord.java] ==> expected: but was: +[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0 diff --git a/jooq/output/12-jooqtest-slice.txt b/jooq/output/12-jooqtest-slice.txt new file mode 100644 index 0000000..0631e1b --- /dev/null +++ b/jooq/output/12-jooqtest-slice.txt @@ -0,0 +1,6 @@ +DSLContext present: true (dialect POSTGRES) +BookshopRepository in context: false +StockService in context: false +SqlLog in context: false +Flyway ran (schema has tables): true +author rows via typed API: 0 diff --git a/jooq/output/13-startup-log-lines.txt b/jooq/output/13-startup-log-lines.txt new file mode 100644 index 0000000..32a7291 --- /dev/null +++ b/jooq/output/13-startup-log-lines.txt @@ -0,0 +1,5 @@ +com.ankurm.jooq.JooqSliceTest : Starting JooqSliceTest using Java 25.0.5.1 with PID N +org.flywaydb.core.FlywayExecutor : Database: jdbc:postgresql://localhost:PORT/test?loggerLevel=OFF (PostgreSQL 17.12) +o.f.core.internal.command.DbMigrate : Successfully applied 2 migrations to schema "public", now at version v2 (execution time 00:00.021s) +Thank you for using jOOQ 3.21.9 (Build date: 2026-09-24T13:35:23Z) +o.j.i.D.logVersionSupport : Version mismatch : Database version is older than what dialect SQLDialect.POSTGRES supports: 17.12. Consider https://www.jooq.org/download/support-matrix to see what jOOQ version and edition supports which RDBMS versions. diff --git a/jooq/output/14-missing-flyway-database-module.txt b/jooq/output/14-missing-flyway-database-module.txt new file mode 100644 index 0000000..faea0e2 --- /dev/null +++ b/jooq/output/14-missing-flyway-database-module.txt @@ -0,0 +1,4 @@ +flyway-database-postgresql removed from the application dependencies +Caused by: org.flywaydb.core.api.FlywayException: Unsupported Database: PostgreSQL 17.12 +[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 9.266 s <<< FAILURE! -- in com.ankurm.jooq.JooqSliceTest +[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 diff --git a/jooq/pom.xml b/jooq/pom.xml new file mode 100644 index 0000000..0dc9a38 --- /dev/null +++ b/jooq/pom.xml @@ -0,0 +1,159 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + com.ankurm + jooq-demo + 1.0.0 + jar + + + 25 + 25 + + jdbc:postgresql://localhost:55432/bookshop + + + + + org.springframework.boot + spring-boot-starter-jooq + + + org.springframework.boot + spring-boot-starter-flyway + + + + org.flywaydb + flyway-database-postgresql + + + org.postgresql + postgresql + runtime + + + + org.springframework.boot + spring-boot-starter-jooq-test + test + + + org.springframework.boot + spring-boot-starter-flyway-test + test + + + org.springframework.boot + spring-boot-testcontainers + test + + + org.testcontainers + testcontainers-postgresql + test + + + org.testcontainers + testcontainers-junit-jupiter + test + + + + org.jooq + jooq-codegen + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + + codegen + + + + org.flywaydb + flyway-maven-plugin + ${flyway.version} + + ${codegen.jdbc.url} + bookshop + bookshop + + filesystem:src/main/resources/db/migration + + + + + org.flywaydb + flyway-database-postgresql + ${flyway.version} + + + org.postgresql + postgresql + ${postgresql.version} + + + + + org.jooq + jooq-codegen-maven + ${jooq.version} + + + org.postgresql + postgresql + ${postgresql.version} + + + + + ${codegen.jdbc.url} + bookshop + bookshop + + + + org.jooq.meta.postgres.PostgresDatabase + public + flyway_schema_history + + + true + true + false + false + false + + + com.ankurm.jooq.generated + src/main/java + + + + + + + + + diff --git a/jooq/scripts/codegen.sh b/jooq/scripts/codegen.sh new file mode 100755 index 0000000..879de74 --- /dev/null +++ b/jooq/scripts/codegen.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Regenerate src/main/java/com/ankurm/jooq/generated from the Flyway migrations. +# 1. start a throwaway PostgreSQL 17 2. flyway:migrate 3. jooq-codegen:generate 4. remove the container +# Usage: scripts/codegen.sh [-Dflyway.target=1] (extra args go to Maven) +set -euo pipefail +cd "$(dirname "$0")/.." +NAME=jooq-codegen-pg +docker rm -f "$NAME" >/dev/null 2>&1 || true +docker run -d --name "$NAME" -p 55432:5432 \ + -e POSTGRES_DB=bookshop -e POSTGRES_USER=bookshop -e POSTGRES_PASSWORD=bookshop \ + postgres:17-alpine >/dev/null +trap 'docker rm -f "$NAME" >/dev/null 2>&1 || true' EXIT +for i in $(seq 1 60); do + docker exec "$NAME" pg_isready -U bookshop -d bookshop >/dev/null 2>&1 && break + sleep 1 +done +sleep 2 +rm -rf src/main/java/com/ankurm/jooq/generated +mvn -B -q -Pcodegen "$@" flyway:migrate jooq-codegen:generate +echo "generated files:" +find src/main/java/com/ankurm/jooq/generated -name '*.java' | sort diff --git a/jooq/scripts/compile-errors.sh b/jooq/scripts/compile-errors.sh new file mode 100755 index 0000000..7f264a0 --- /dev/null +++ b/jooq/scripts/compile-errors.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Shows what the compiler says in three situations. Works on a throwaway copy of the module. +# A. wrong Java type in a condition (BOOK.PRICE.eq("12.50")) +# B. a column name typo (BOOK.ISBNN) +# C. the schema changes under existing code (regenerate WITHOUT migration V2: BOOK.ISBN disappears) +set -uo pipefail +HERE="$(cd "$(dirname "$0")/.." && pwd)" +OUT="$HERE/output/10-compile-errors.txt" +WORK="$(mktemp -d)" +filter() { sed -e '/Failed to execute goal/,$d' | grep -v -E 'Picked up|^WARNING|COMPILATION ERROR|^\[ERROR\] *$|^[[:space:]]*$' | sed -e "s#/tmp/[^ ]*/m/##" -e 's/^\[ERROR\] //' -e 's/\x1b\[[0-9;]*m//g'; } + +mkdir -p "$WORK/m" && cp -r "$HERE/pom.xml" "$HERE/src" "$HERE/scripts" "$WORK/m/" +cd "$WORK/m" +: > "$OUT" + +echo "== A. wrong type: BOOK.PRICE.eq(\"12.50\") ==" >> "$OUT" +cp "$HERE/src/broken/WrongType.java" src/main/java/com/ankurm/jooq/ +mvn -B -q compile 2>&1 | filter >> "$OUT" +rm src/main/java/com/ankurm/jooq/WrongType.java + +echo >> "$OUT"; echo "== B. typo: BOOK.ISBNN ==" >> "$OUT" +cp "$HERE/src/broken/Typo.java" src/main/java/com/ankurm/jooq/ +mvn -B -q compile 2>&1 | filter >> "$OUT" +rm src/main/java/com/ankurm/jooq/Typo.java + +echo >> "$OUT"; echo "== C. regenerate from schema version 1 only (no isbn column), compile the unchanged application ==" >> "$OUT" +"$WORK/m/scripts/codegen.sh" -Dflyway.target=1 > /dev/null 2>&1 +mvn -B -q compile 2>&1 | filter >> "$OUT" +cd "$HERE"; rm -rf "$WORK" +cat "$OUT" diff --git a/jooq/scripts/container-trap.sh b/jooq/scripts/container-trap.sh new file mode 100755 index 0000000..d78c063 --- /dev/null +++ b/jooq/scripts/container-trap.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Reproduces the Testcontainers + Spring context-cache trap: a per-class @Container is stopped after +# the first test class, but Spring reuses the cached ApplicationContext (and its connection pool) for the next one. +set -uo pipefail +HERE="$(cd "$(dirname "$0")/.." && pwd)" +OUT="$HERE/output/09-container-lifecycle-trap.txt" +WORK="$(mktemp -d)" +mkdir -p "$WORK/m" && cp -r "$HERE/pom.xml" "$HERE/src" "$WORK/m/" +cd "$WORK/m" +python3 - <<'PY' +p='src/test/java/com/ankurm/jooq/PostgresTestBase.java' +s=open(p).read() +s=s.replace('@SpringBootTest\nabstract','@org.testcontainers.junit.jupiter.Testcontainers\n@SpringBootTest\nabstract') +s=s.replace(' @ServiceConnection\n static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");\n\n static {\n postgres.start();\n }\n', + ' @org.testcontainers.junit.jupiter.Container\n @ServiceConnection\n static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");\n') +open(p,'w').write(s) +PY +{ + echo "per-class @Container, two test classes sharing one cached Spring context (hikari connection-timeout shortened to 2 s)" + mvn -B -q test -DargLine="-Dspring.datasource.hikari.connection-timeout=2000" -Dtest='TransactionTests,QueryTests' 2>&1 \ + | grep -E 'Tests run:|TransientDataAccessResourceException|Connection is not available|Failed to validate connection' | sed 's/^[0-9:.]* //' | sed -E 's/PgConnection@[0-9a-f]+/PgConnection@HASH/; s/^[0-9T:.+-]+ +//' | sort | uniq -c | sed 's/^ *//' | cut -c1-260 | head -12 +} > "$OUT" +cd "$HERE"; rm -rf "$WORK" +cat "$OUT" diff --git a/jooq/scripts/drift-demo.sh b/jooq/scripts/drift-demo.sh new file mode 100755 index 0000000..e97edc9 --- /dev/null +++ b/jooq/scripts/drift-demo.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# What happens when someone adds a migration but forgets to regenerate: run the drift test on a +# throwaway copy that has an extra migration V3. +set -uo pipefail +HERE="$(cd "$(dirname "$0")/.." && pwd)" +OUT="$HERE/output/11-drift-detected.txt" +WORK="$(mktemp -d)" +mkdir -p "$WORK/m" && cp -r "$HERE/pom.xml" "$HERE/src" "$WORK/m/" +cd "$WORK/m" +cat > src/main/resources/db/migration/V3__book_subtitle.sql <<'SQL' +ALTER TABLE book ADD COLUMN subtitle TEXT; +SQL +{ + echo "added src/main/resources/db/migration/V3__book_subtitle.sql, did NOT regenerate" + mvn -B -q test -Dtest=CodegenDriftTest 2>&1 | grep -E 'Tests run:|AssertionFailedError|generated code is stale' | head -5 | cut -c1-400 +} > "$OUT" +cd "$HERE"; rm -rf "$WORK" +cat "$OUT" diff --git a/jooq/scripts/missing-flyway-module.sh b/jooq/scripts/missing-flyway-module.sh new file mode 100755 index 0000000..8a08dff --- /dev/null +++ b/jooq/scripts/missing-flyway-module.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# What a Flyway 12 + PostgreSQL project does without the separate flyway-database-postgresql module. +set -uo pipefail +HERE="$(cd "$(dirname "$0")/.." && pwd)" +OUT="$HERE/output/14-missing-flyway-database-module.txt" +WORK="$(mktemp -d)" +mkdir -p "$WORK/m" && cp -r "$HERE/pom.xml" "$HERE/src" "$WORK/m/" +cd "$WORK/m" +python3 - <<'PY' +import re +s=open('pom.xml').read() +s=s.replace(''' + org.flywaydb + flyway-database-postgresql + +''','',1) +open('pom.xml','w').write(s) +PY +{ + echo "flyway-database-postgresql removed from the application dependencies" + mvn -B -q test -Dtest=JooqSliceTest 2>&1 | grep -E 'Caused by: org.flywaydb.core.api.FlywayException|Tests run:.*Fail' | sed -E 's/^[0-9T:.+-]+ +(WARN|ERROR|INFO) +[0-9]+ --- \[[^]]*\] \[[^]]*\] //' | awk '!s[$0]++' | cut -c1-300 | head -6 +} > "$OUT" +cd "$HERE"; rm -rf "$WORK" +cat "$OUT" diff --git a/jooq/scripts/run-all.sh b/jooq/scripts/run-all.sh new file mode 100755 index 0000000..31942ee --- /dev/null +++ b/jooq/scripts/run-all.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs Docker (Testcontainers starts PostgreSQL 17) and JDK 25. +# 01-08, 12 written by the test suite (each test also asserts what it prints) +# 09, 10, 11 written by scripts that break a throwaway copy of the module on purpose +# 00 the code generator run (scripts/codegen.sh) +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -B -q test +scripts/container-trap.sh >/dev/null +scripts/compile-errors.sh >/dev/null +scripts/drift-demo.sh >/dev/null +scripts/startup-warnings.sh >/dev/null +scripts/missing-flyway-module.sh >/dev/null +sums() { find src/main/java/com/ankurm/jooq/generated -name '*.java' | sort | xargs sha256sum | sha256sum | cut -c1-16; } +BEFORE="$(sums)" +{ + echo "\$ scripts/codegen.sh" + scripts/codegen.sh 2>&1 | grep -v -E 'Picked up|^WARNING' + echo + echo "checksum of generated sources before: $BEFORE" + echo "checksum of generated sources after: $(sums)" +} > output/00-codegen-run.txt +echo "wrote:"; ls output diff --git a/jooq/scripts/startup-warnings.sh b/jooq/scripts/startup-warnings.sh new file mode 100755 index 0000000..d8649ac --- /dev/null +++ b/jooq/scripts/startup-warnings.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Captures the startup lines a reader will see in the log: the jOOQ banner version and the dialect WARN. +set -uo pipefail +cd "$(dirname "$0")/.." +{ + mvn -B -q test -Dtest=JooqSliceTest 2>&1 | grep -E 'Thank you for using jOOQ|Version mismatch|PostgreSQL 17|Successfully applied|Starting JooqSliceTest' \ + | sed -E 's/localhost:[0-9]+/localhost:PORT/; s/^[0-9T:.+-]+ +(INFO|WARN) +[0-9]+ --- \[[^]]*\] \[[^]]*\] //; s/ +/ /g; s/PID [0-9]+/PID N/; s/ \(started by [^)]*\)//; s/@+ +//' +} > output/13-startup-log-lines.txt +cat output/13-startup-log-lines.txt diff --git a/jooq/src/broken/Typo.java b/jooq/src/broken/Typo.java new file mode 100644 index 0000000..f222367 --- /dev/null +++ b/jooq/src/broken/Typo.java @@ -0,0 +1,12 @@ +package com.ankurm.jooq; + +import org.jooq.DSLContext; + +import static com.ankurm.jooq.generated.Tables.BOOK; + +/** NOT part of the build. Same typo as the runtime test ("isbnn"), but in the typed API. */ +class Typo { + Object find(DSLContext dsl) { + return dsl.select(BOOK.ISBNN).from(BOOK).fetch(); + } +} diff --git a/jooq/src/broken/WrongType.java b/jooq/src/broken/WrongType.java new file mode 100644 index 0000000..bfae203 --- /dev/null +++ b/jooq/src/broken/WrongType.java @@ -0,0 +1,12 @@ +package com.ankurm.jooq; + +import org.jooq.DSLContext; + +import static com.ankurm.jooq.generated.Tables.BOOK; + +/** NOT part of the build. scripts/compile-errors.sh copies it into a throwaway copy of the module. */ +class WrongType { + Object find(DSLContext dsl) { + return dsl.selectFrom(BOOK).where(BOOK.PRICE.eq("12.50")).fetch(); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/BookshopRepository.java b/jooq/src/main/java/com/ankurm/jooq/BookshopRepository.java new file mode 100644 index 0000000..06b730e --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/BookshopRepository.java @@ -0,0 +1,152 @@ +package com.ankurm.jooq; + +import com.ankurm.jooq.Views.*; +import com.ankurm.jooq.generated.enums.Genre; +import com.ankurm.jooq.generated.tables.pojos.Book; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Records; +import org.springframework.stereotype.Repository; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import static com.ankurm.jooq.generated.Tables.*; +import static org.jooq.impl.DSL.*; + +/** + * Every query in this class is built from generated classes (BOOK, AUTHOR, REVIEW), so a column + * that no longer exists is a compile error rather than a runtime one. + */ +@Repository +public class BookshopRepository { + + private final DSLContext dsl; + + public BookshopRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public long insertAuthor(String name, String country) { + // INSERT ... RETURNING id: one round trip, typed as Long + return dsl.insertInto(AUTHOR) + .columns(AUTHOR.NAME, AUTHOR.COUNTRY) + .values(name, country) + .returning(AUTHOR.ID) + .fetchSingle() + .getId(); + } + + public Book insertBook(long authorId, String title, Genre genre, String price, String publishedOn, int stock, String isbn) { + return dsl.insertInto(BOOK) + .set(BOOK.AUTHOR_ID, authorId) + .set(BOOK.TITLE, title) + .set(BOOK.GENRE, genre) + .set(BOOK.PRICE, new BigDecimal(price)) + .set(BOOK.PUBLISHED_ON, java.time.LocalDate.parse(publishedOn)) + .set(BOOK.STOCK, stock) + .set(BOOK.ISBN, isbn) + .returning() + .fetchSingle() + .into(Book.class); // generated record -> generated Java record POJO + } + + public void addReview(long bookId, int rating, String body) { + dsl.insertInto(REVIEW) + .set(REVIEW.BOOK_ID, bookId) + .set(REVIEW.RATING, (short) rating) + .set(REVIEW.BODY, body) + .execute(); + } + + /** Dynamic WHERE: each optional filter adds a Condition, null filters add nothing. */ + public List search(BookFilter f) { + List conditions = new ArrayList<>(); + if (f.titleContains() != null) conditions.add(BOOK.TITLE.containsIgnoreCase(f.titleContains())); + if (f.genre() != null) conditions.add(BOOK.GENRE.eq(f.genre())); + if (f.maxPrice() != null) conditions.add(BOOK.PRICE.le(f.maxPrice())); + if (f.authorCountry() != null) conditions.add(AUTHOR.COUNTRY.eq(f.authorCountry())); + + return dsl.select(BOOK.TITLE, AUTHOR.NAME, BOOK.GENRE, BOOK.PRICE) + .from(BOOK) + .join(AUTHOR).on(AUTHOR.ID.eq(BOOK.AUTHOR_ID)) + .where(conditions) // an empty list renders no WHERE at all + .orderBy(BOOK.TITLE) + .fetch(Records.mapping(BookRow::new)); + } + + /** Parent and children in one statement, without a join that multiplies rows. */ + public List booksWithReviews() { + return dsl.select( + BOOK.TITLE, + multiset(select(REVIEW.RATING, REVIEW.BODY) + .from(REVIEW) + .where(REVIEW.BOOK_ID.eq(BOOK.ID)) + .orderBy(REVIEW.ID)) + .convertFrom(r -> r.map(Records.mapping(ReviewView::new)))) + .from(BOOK) + .orderBy(BOOK.TITLE) + .fetch(Records.mapping(BookWithReviews::new)); + } + + /** A CTE plus a window function: the best-rated book per genre. */ + public List topRatedPerGenre() { + var ratings = name("ratings").as( + select(BOOK.GENRE, BOOK.TITLE, avg(REVIEW.RATING.cast(Double.class)).as("avg_rating")) + .from(BOOK).join(REVIEW).on(REVIEW.BOOK_ID.eq(BOOK.ID)) + .groupBy(BOOK.GENRE, BOOK.TITLE)); + var genre = ratings.field(BOOK.GENRE); + var title = ratings.field(BOOK.TITLE); + var avgRating = ratings.field("avg_rating", Double.class); + var rank = rank().over(partitionBy(genre).orderBy(avgRating.desc(), title)).as("rnk"); + + var ranked = name("ranked").as(select(genre, title, avgRating, rank).from(ratings)); + return dsl.with(ratings).with(ranked) + .select(ranked.field(genre), ranked.field(title), ranked.field(avgRating), ranked.field(rank)) + .from(ranked) + .where(ranked.field(rank).eq(1)) + .orderBy(ranked.field(genre)) + .fetch(Records.mapping(GenreLeader::new)); + } + + public List authorLeaderboard() { + return dsl.select(AUTHOR.NAME, count(), sum(BOOK.PRICE.times(BOOK.STOCK))) + .from(AUTHOR).join(BOOK).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)) + .groupBy(AUTHOR.NAME) + .orderBy(sum(BOOK.PRICE.times(BOOK.STOCK)).desc()) + .fetch(r -> new LeaderboardRow(r.value1(), r.value2(), r.value3())); + } + + /** Insert, or add to the stock if the ISBN already exists. */ + public Book upsertByIsbn(long authorId, String isbn, String title, int stock) { + return dsl.insertInto(BOOK) + .set(BOOK.AUTHOR_ID, authorId) + .set(BOOK.TITLE, title) + .set(BOOK.GENRE, Genre.TECH) + .set(BOOK.PRICE, new BigDecimal("10.00")) + .set(BOOK.PUBLISHED_ON, java.time.LocalDate.parse("2026-01-01")) + .set(BOOK.STOCK, stock) + .set(BOOK.ISBN, isbn) + .onConflict(BOOK.ISBN) + .doUpdate() + .set(BOOK.STOCK, BOOK.STOCK.plus(stock)) + .returning() + .fetchSingle() + .into(Book.class); + } + + /** Keyset ("seek") pagination: WHERE id > ? ORDER BY id LIMIT ?, no OFFSET. */ + public KeysetPage pageAfter(Long afterId, int size) { + List ids = dsl.select(BOOK.ID).from(BOOK) + .orderBy(BOOK.ID) + .seek(afterId == null ? 0L : afterId) + .limit(size) + .fetch(BOOK.ID); + return new KeysetPage(ids, ids.size() == size ? ids.getLast() : null); + } + + public int countBooks() { + return dsl.fetchCount(BOOK); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/JooqDemoApplication.java b/jooq/src/main/java/com/ankurm/jooq/JooqDemoApplication.java new file mode 100644 index 0000000..c429eda --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/JooqDemoApplication.java @@ -0,0 +1,11 @@ +package com.ankurm.jooq; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class JooqDemoApplication { + public static void main(String[] args) { + SpringApplication.run(JooqDemoApplication.class, args); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/SqlLog.java b/jooq/src/main/java/com/ankurm/jooq/SqlLog.java new file mode 100644 index 0000000..de1b182 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/SqlLog.java @@ -0,0 +1,37 @@ +package com.ankurm.jooq; + +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListener; +import org.jooq.ExecuteListenerProvider; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Records the SQL jOOQ actually sends. + * + * It implements ExecuteListenerProvider on purpose: Spring Boot's JooqAutoConfiguration collects + * ExecuteListenerProvider beans (read from the 4.2.0 jar with javap), NOT plain ExecuteListener beans. + * A bean that only implements ExecuteListener is silently never called + * (see output/02-autoconfig-and-insert-returning.txt). + */ +@Component +public class SqlLog implements ExecuteListener, ExecuteListenerProvider { + + private final List statements = new CopyOnWriteArrayList<>(); + + @Override + public ExecuteListener provide() { + return this; + } + + @Override + public void renderEnd(ExecuteContext ctx) { + statements.add(ctx.sql()); + } + + public void clear() { statements.clear(); } + + public List statements() { return List.copyOf(statements); } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/StockService.java b/jooq/src/main/java/com/ankurm/jooq/StockService.java new file mode 100644 index 0000000..047c369 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/StockService.java @@ -0,0 +1,87 @@ +package com.ankurm.jooq; + +import com.ankurm.jooq.generated.enums.Genre; +import org.jooq.DSLContext; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; + +import static com.ankurm.jooq.generated.Tables.AUTHOR; +import static com.ankurm.jooq.generated.Tables.BOOK; + +/** Transaction behaviour of jOOQ under Spring. Each method is exercised by a test. */ +@Service +public class StockService { + + private final DSLContext dsl; + private final BookshopRepository repo; + + public StockService(DSLContext dsl, BookshopRepository repo) { + this.dsl = dsl; + this.repo = repo; + } + + /** No transaction: every statement commits on its own. */ + public void noTransactionThenFail() { + long a = repo.insertAuthor("No Tx Author", "US"); + repo.insertBook(a, "Persisted Before The Failure", Genre.TECH, "9.99", "2026-01-01", 1, "NT-1"); + throw new IllegalStateException("boom after two committed statements"); + } + + @Transactional + public void springTransactionRuntimeFailure() { + long a = repo.insertAuthor("Rolled Back Author", "US"); + repo.insertBook(a, "Rolled Back Book", Genre.TECH, "9.99", "2026-01-01", 1, "RB-1"); + throw new IllegalStateException("runtime exception: Spring rolls back"); + } + + @Transactional + public void springTransactionCheckedFailure() throws IOException { + long a = repo.insertAuthor("Checked Author", "US"); + repo.insertBook(a, "Checked Book", Genre.TECH, "9.99", "2026-01-01", 1, "CK-1"); + throw new IOException("checked exception: Spring COMMITS by default"); + } + + @Transactional(rollbackFor = Exception.class) + public void springTransactionCheckedFailureWithRollbackFor() throws IOException { + long a = repo.insertAuthor("Checked Author 2", "US"); + repo.insertBook(a, "Checked Book 2", Genre.TECH, "9.99", "2026-01-01", 1, "CK-2"); + throw new IOException("checked exception with rollbackFor: rolled back"); + } + + /** dsl.transaction(...) inside @Transactional: the inner block is a savepoint. */ + @Transactional + public String nestedTransactionSavepoint() { + long a = repo.insertAuthor("Outer Author", "US"); + try { + dsl.transaction(cfg -> { + cfg.dsl().insertInto(AUTHOR).set(AUTHOR.NAME, "Inner Author").set(AUTHOR.COUNTRY, "US").execute(); + throw new IllegalStateException("inner block fails"); + }); + } catch (IllegalStateException e) { + return "caught inner failure, outer continues (author id " + a + ")"; + } + return "unreachable"; + } + + /** dsl.transaction(...) with no surrounding @Transactional. */ + public void jooqTransactionOnly(String name, boolean fail) { + dsl.transaction(cfg -> { + cfg.dsl().insertInto(AUTHOR).set(AUTHOR.NAME, name).set(AUTHOR.COUNTRY, "DE").execute(); + if (fail) throw new IllegalStateException("fail inside dsl.transaction"); + }); + } + + /** Optimistic update guarded in SQL: returns the number of rows changed. */ + @Transactional + public int sellOne(long bookId) { + return dsl.update(BOOK).set(BOOK.STOCK, BOOK.STOCK.minus(1)) + .where(BOOK.ID.eq(bookId).and(BOOK.STOCK.gt(0))).execute(); + } + + public BigDecimal totalValue() { + return dsl.select(org.jooq.impl.DSL.sum(BOOK.PRICE.times(BOOK.STOCK))).from(BOOK).fetchSingle().value1(); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/Views.java b/jooq/src/main/java/com/ankurm/jooq/Views.java new file mode 100644 index 0000000..5247cad --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/Views.java @@ -0,0 +1,31 @@ +package com.ankurm.jooq; + +import com.ankurm.jooq.generated.enums.Genre; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; + +/** Plain Java records that jOOQ fills straight from a query. No mapping annotations, no entities. */ +public final class Views { + private Views() {} + + /** Optional filters for {@link BookshopRepository#search}. Any field may be null. */ + public record BookFilter(String titleContains, Genre genre, BigDecimal maxPrice, String authorCountry) {} + + /** One row of the search result: columns from two tables, no entity graph. */ + public record BookRow(String title, String author, Genre genre, BigDecimal price) {} + + public record ReviewView(short rating, String body) {} + + /** A book with its reviews nested inside it, produced by ONE SQL statement (MULTISET). */ + public record BookWithReviews(String title, List reviews) {} + + public record GenreLeader(Genre genre, String title, double avgRating, int rank) {} + + public record KeysetPage(List ids, Long next) {} + + public record LeaderboardRow(String author, long books, BigDecimal catalogueValue) {} + + public record DayStock(LocalDate published, int stock) {} +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/DefaultCatalog.java b/jooq/src/main/java/com/ankurm/jooq/generated/DefaultCatalog.java new file mode 100644 index 0000000..3364c83 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/DefaultCatalog.java @@ -0,0 +1,54 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated; + + +import java.util.Arrays; +import java.util.List; + +import org.jooq.Constants; +import org.jooq.Schema; +import org.jooq.impl.CatalogImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class DefaultCatalog extends CatalogImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of DEFAULT_CATALOG + */ + public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog(); + + /** + * standard public schema + */ + public final Public PUBLIC = Public.PUBLIC; + + /** + * No further instances allowed + */ + private DefaultCatalog() { + super(""); + } + + @Override + public final List getSchemas() { + return Arrays.asList( + Public.PUBLIC + ); + } + + /** + * A reference to the 3.21 minor release of the code generator. If this + * doesn't compile, it's because the runtime library uses an older minor + * release, namely: 3.21. You can turn off the generation of this reference + * by specifying /configuration/generator/generate/jooqVersionReference + */ + private static final String REQUIRE_RUNTIME_JOOQ_VERSION = Constants.VERSION_3_21; +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/Indexes.java b/jooq/src/main/java/com/ankurm/jooq/generated/Indexes.java new file mode 100644 index 0000000..6c0cb95 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/Indexes.java @@ -0,0 +1,28 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated; + + +import com.ankurm.jooq.generated.tables.Book; +import com.ankurm.jooq.generated.tables.Review; + +import org.jooq.Index; +import org.jooq.OrderField; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; + + +/** + * A class modelling indexes of tables in public. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Indexes { + + // ------------------------------------------------------------------------- + // INDEX definitions + // ------------------------------------------------------------------------- + + public static final Index BOOK_AUTHOR_IDX = Internal.createIndex(DSL.name("book_author_idx"), Book.BOOK, new OrderField[] { Book.BOOK.AUTHOR_ID }, false); + public static final Index REVIEW_BOOK_IDX = Internal.createIndex(DSL.name("review_book_idx"), Review.REVIEW, new OrderField[] { Review.REVIEW.BOOK_ID }, false); +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/Keys.java b/jooq/src/main/java/com/ankurm/jooq/generated/Keys.java new file mode 100644 index 0000000..5b53775 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/Keys.java @@ -0,0 +1,44 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated; + + +import com.ankurm.jooq.generated.tables.Author; +import com.ankurm.jooq.generated.tables.Book; +import com.ankurm.jooq.generated.tables.Review; +import com.ankurm.jooq.generated.tables.records.AuthorRecord; +import com.ankurm.jooq.generated.tables.records.BookRecord; +import com.ankurm.jooq.generated.tables.records.ReviewRecord; + +import org.jooq.ForeignKey; +import org.jooq.TableField; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; +import org.jooq.impl.QOM.ForeignKeyRule; + + +/** + * A class modelling foreign key relationships and constraints of tables in + * public. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Keys { + + // ------------------------------------------------------------------------- + // UNIQUE and PRIMARY KEY definitions + // ------------------------------------------------------------------------- + + public static final UniqueKey AUTHOR_PKEY = Internal.createUniqueKey(Author.AUTHOR, DSL.name("author_pkey"), new TableField[] { Author.AUTHOR.ID }, true); + public static final UniqueKey BOOK_ISBN_KEY = Internal.createUniqueKey(Book.BOOK, DSL.name("book_isbn_key"), new TableField[] { Book.BOOK.ISBN }, true); + public static final UniqueKey BOOK_PKEY = Internal.createUniqueKey(Book.BOOK, DSL.name("book_pkey"), new TableField[] { Book.BOOK.ID }, true); + public static final UniqueKey REVIEW_PKEY = Internal.createUniqueKey(Review.REVIEW, DSL.name("review_pkey"), new TableField[] { Review.REVIEW.ID }, true); + + // ------------------------------------------------------------------------- + // FOREIGN KEY definitions + // ------------------------------------------------------------------------- + + public static final ForeignKey BOOK__BOOK_AUTHOR_ID_FKEY = Internal.createForeignKey(Book.BOOK, DSL.name("book_author_id_fkey"), new TableField[] { Book.BOOK.AUTHOR_ID }, Keys.AUTHOR_PKEY, new TableField[] { Author.AUTHOR.ID }, true, ForeignKeyRule.NO_ACTION, ForeignKeyRule.NO_ACTION); + public static final ForeignKey REVIEW__REVIEW_BOOK_ID_FKEY = Internal.createForeignKey(Review.REVIEW, DSL.name("review_book_id_fkey"), new TableField[] { Review.REVIEW.BOOK_ID }, Keys.BOOK_PKEY, new TableField[] { Book.BOOK.ID }, true, ForeignKeyRule.NO_ACTION, ForeignKeyRule.NO_ACTION); +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/Public.java b/jooq/src/main/java/com/ankurm/jooq/generated/Public.java new file mode 100644 index 0000000..8d47ef7 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/Public.java @@ -0,0 +1,69 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated; + + +import com.ankurm.jooq.generated.tables.Author; +import com.ankurm.jooq.generated.tables.Book; +import com.ankurm.jooq.generated.tables.Review; + +import java.util.Arrays; +import java.util.List; + +import org.jooq.Catalog; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.jooq.impl.SchemaImpl; + + +/** + * standard public schema + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Public extends SchemaImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of public + */ + public static final Public PUBLIC = new Public(); + + /** + * The table public.author. + */ + public final Author AUTHOR = Author.AUTHOR; + + /** + * The table public.book. + */ + public final Book BOOK = Book.BOOK; + + /** + * The table public.review. + */ + public final Review REVIEW = Review.REVIEW; + + /** + * No further instances allowed + */ + private Public() { + super(DSL.name("public"), null, DSL.comment("standard public schema")); + } + + + @Override + public Catalog getCatalog() { + return DefaultCatalog.DEFAULT_CATALOG; + } + + @Override + public final List> getTables() { + return Arrays.asList( + Author.AUTHOR, + Book.BOOK, + Review.REVIEW + ); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/Tables.java b/jooq/src/main/java/com/ankurm/jooq/generated/Tables.java new file mode 100644 index 0000000..f9bdfcf --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/Tables.java @@ -0,0 +1,32 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated; + + +import com.ankurm.jooq.generated.tables.Author; +import com.ankurm.jooq.generated.tables.Book; +import com.ankurm.jooq.generated.tables.Review; + + +/** + * Convenience access to all tables in public. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Tables { + + /** + * The table public.author. + */ + public static final Author AUTHOR = Author.AUTHOR; + + /** + * The table public.book. + */ + public static final Book BOOK = Book.BOOK; + + /** + * The table public.review. + */ + public static final Review REVIEW = Review.REVIEW; +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/enums/Genre.java b/jooq/src/main/java/com/ankurm/jooq/generated/enums/Genre.java new file mode 100644 index 0000000..911c64a --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/enums/Genre.java @@ -0,0 +1,62 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.enums; + + +import com.ankurm.jooq.generated.Public; + +import org.jooq.Catalog; +import org.jooq.EnumType; +import org.jooq.Schema; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public enum Genre implements EnumType { + + FICTION("FICTION"), + + SCIENCE("SCIENCE"), + + HISTORY("HISTORY"), + + TECH("TECH"); + + private final String literal; + + private Genre(String literal) { + this.literal = literal; + } + + @Override + public Catalog getCatalog() { + return getSchema().getCatalog(); + } + + @Override + public Schema getSchema() { + return Public.PUBLIC; + } + + @Override + public String getName() { + return "genre"; + } + + @Override + public String getLiteral() { + return literal; + } + + /** + * Lookup a value of this EnumType by its literal. Returns + * null, if no such value could be found, see {@link + * EnumType#lookupLiteral(Class, String)}. + */ + public static Genre lookupLiteral(String literal) { + return EnumType.lookupLiteral(Genre.class, literal); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/Author.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/Author.java new file mode 100644 index 0000000..5ab0399 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/Author.java @@ -0,0 +1,285 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables; + + +import com.ankurm.jooq.generated.Keys; +import com.ankurm.jooq.generated.Public; +import com.ankurm.jooq.generated.tables.Book.BookPath; +import com.ankurm.jooq.generated.tables.records.AuthorRecord; + +import java.util.Collection; + +import org.jooq.Condition; +import org.jooq.Field; +import org.jooq.ForeignKey; +import org.jooq.Identity; +import org.jooq.InverseForeignKey; +import org.jooq.Name; +import org.jooq.Path; +import org.jooq.PlainSQL; +import org.jooq.QueryPart; +import org.jooq.Record; +import org.jooq.SQL; +import org.jooq.Schema; +import org.jooq.Stringly; +import org.jooq.Table; +import org.jooq.TableField; +import org.jooq.TableLike; +import org.jooq.TableOptions; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; +import org.jooq.impl.SQLDataType; +import org.jooq.impl.TableImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Author extends TableImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of public.author + */ + public static final Author AUTHOR = new Author(); + + /** + * The class holding records for this type + */ + @Override + public Class getRecordType() { + return AuthorRecord.class; + } + + /** + * The column public.author.id. + */ + public final TableField ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).generatedAlwaysAsIdentity(), this, ""); + + /** + * The column public.author.name. + */ + public final TableField NAME = createField(DSL.name("name"), SQLDataType.CLOB.nullable(false), this, ""); + + /** + * The column public.author.country. + */ + public final TableField COUNTRY = createField(DSL.name("country"), SQLDataType.CHAR(2).nullable(false), this, ""); + + private Author(Name alias, Table aliased) { + this(alias, aliased, (Field[]) null, null); + } + + private Author(Name alias, Table aliased, Field[] parameters, Condition where) { + super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table(), where); + } + + /** + * Create an aliased public.author table reference + */ + public Author(String alias) { + this(DSL.name(alias), AUTHOR); + } + + /** + * Create an aliased public.author table reference + */ + public Author(Name alias) { + this(alias, AUTHOR); + } + + /** + * Create a public.author table reference + */ + public Author() { + this(DSL.name("author"), null); + } + + public Author(Table path, ForeignKey childPath, InverseForeignKey parentPath) { + super(path, childPath, parentPath, AUTHOR); + } + + /** + * A subtype implementing {@link Path} for simplified path-based joins. + */ + public static class AuthorPath extends Author implements Path { + + private static final long serialVersionUID = 1L; + public AuthorPath(Table path, ForeignKey childPath, InverseForeignKey parentPath) { + super(path, childPath, parentPath); + } + private AuthorPath(Name alias, Table aliased) { + super(alias, aliased); + } + + @Override + public AuthorPath as(String alias) { + return new AuthorPath(DSL.name(alias), this); + } + + @Override + public AuthorPath as(Name alias) { + return new AuthorPath(alias, this); + } + + @Override + public AuthorPath as(Table alias) { + return new AuthorPath(alias.getQualifiedName(), this); + } + } + + @Override + public Schema getSchema() { + return aliased() ? null : Public.PUBLIC; + } + + @Override + public Identity getIdentity() { + return (Identity) super.getIdentity(); + } + + @Override + public UniqueKey getPrimaryKey() { + return Keys.AUTHOR_PKEY; + } + + private transient BookPath _book; + + /** + * Get the implicit to-many join path to the public.book table + */ + public BookPath book() { + if (_book == null) + _book = new BookPath(this, null, Keys.BOOK__BOOK_AUTHOR_ID_FKEY.getInverseKey()); + + return _book; + } + + @Override + public Author as(String alias) { + return new Author(DSL.name(alias), this); + } + + @Override + public Author as(Name alias) { + return new Author(alias, this); + } + + @Override + public Author as(Table alias) { + return new Author(alias.getQualifiedName(), this); + } + + /** + * Rename this table + */ + @Override + public Author rename(String name) { + return new Author(DSL.name(name), null); + } + + /** + * Rename this table + */ + @Override + public Author rename(Name name) { + return new Author(name, null); + } + + /** + * Rename this table + */ + @Override + public Author rename(Table name) { + return new Author(name.getQualifiedName(), null); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Author where(Condition condition) { + return new Author(getQualifiedName(), aliased() ? this : null, null, Internal.condition(this, condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Author where(Collection conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Author where(Condition... conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Author where(Field condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Author where(SQL condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Author where(@Stringly.SQL String condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Author where(@Stringly.SQL String condition, Object... binds) { + return where(DSL.condition(condition, binds)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Author where(@Stringly.SQL String condition, QueryPart... parts) { + return where(DSL.condition(condition, parts)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Author whereExists(TableLike select) { + return where(DSL.exists(select)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Author whereNotExists(TableLike select) { + return where(DSL.notExists(select)); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/Book.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/Book.java new file mode 100644 index 0000000..860fe01 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/Book.java @@ -0,0 +1,354 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables; + + +import com.ankurm.jooq.generated.Indexes; +import com.ankurm.jooq.generated.Keys; +import com.ankurm.jooq.generated.Public; +import com.ankurm.jooq.generated.enums.Genre; +import com.ankurm.jooq.generated.tables.Author.AuthorPath; +import com.ankurm.jooq.generated.tables.Review.ReviewPath; +import com.ankurm.jooq.generated.tables.records.BookRecord; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.jooq.Check; +import org.jooq.Condition; +import org.jooq.Field; +import org.jooq.ForeignKey; +import org.jooq.Identity; +import org.jooq.Index; +import org.jooq.InverseForeignKey; +import org.jooq.Name; +import org.jooq.Path; +import org.jooq.PlainSQL; +import org.jooq.QueryPart; +import org.jooq.Record; +import org.jooq.SQL; +import org.jooq.Schema; +import org.jooq.Stringly; +import org.jooq.Table; +import org.jooq.TableField; +import org.jooq.TableLike; +import org.jooq.TableOptions; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; +import org.jooq.impl.SQLDataType; +import org.jooq.impl.TableImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Book extends TableImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of public.book + */ + public static final Book BOOK = new Book(); + + /** + * The class holding records for this type + */ + @Override + public Class getRecordType() { + return BookRecord.class; + } + + /** + * The column public.book.id. + */ + public final TableField ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).generatedAlwaysAsIdentity(), this, ""); + + /** + * The column public.book.author_id. + */ + public final TableField AUTHOR_ID = createField(DSL.name("author_id"), SQLDataType.BIGINT.nullable(false), this, ""); + + /** + * The column public.book.title. + */ + public final TableField TITLE = createField(DSL.name("title"), SQLDataType.CLOB.nullable(false), this, ""); + + /** + * The column public.book.genre. + */ + public final TableField GENRE = createField(DSL.name("genre"), SQLDataType.VARCHAR.nullable(false).asEnumDataType(Genre.class), this, ""); + + /** + * The column public.book.price. + */ + public final TableField PRICE = createField(DSL.name("price"), SQLDataType.NUMERIC(10, 2).nullable(false), this, ""); + + /** + * The column public.book.published_on. + */ + public final TableField PUBLISHED_ON = createField(DSL.name("published_on"), SQLDataType.LOCALDATE.nullable(false), this, ""); + + /** + * The column public.book.stock. + */ + public final TableField STOCK = createField(DSL.name("stock"), SQLDataType.INTEGER.nullable(false).defaultValue(DSL.field(DSL.raw("0"), SQLDataType.INTEGER)), this, ""); + + /** + * The column public.book.isbn. + */ + public final TableField ISBN = createField(DSL.name("isbn"), SQLDataType.CLOB.nullable(false), this, ""); + + private Book(Name alias, Table aliased) { + this(alias, aliased, (Field[]) null, null); + } + + private Book(Name alias, Table aliased, Field[] parameters, Condition where) { + super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table(), where); + } + + /** + * Create an aliased public.book table reference + */ + public Book(String alias) { + this(DSL.name(alias), BOOK); + } + + /** + * Create an aliased public.book table reference + */ + public Book(Name alias) { + this(alias, BOOK); + } + + /** + * Create a public.book table reference + */ + public Book() { + this(DSL.name("book"), null); + } + + public Book(Table path, ForeignKey childPath, InverseForeignKey parentPath) { + super(path, childPath, parentPath, BOOK); + } + + /** + * A subtype implementing {@link Path} for simplified path-based joins. + */ + public static class BookPath extends Book implements Path { + + private static final long serialVersionUID = 1L; + public BookPath(Table path, ForeignKey childPath, InverseForeignKey parentPath) { + super(path, childPath, parentPath); + } + private BookPath(Name alias, Table aliased) { + super(alias, aliased); + } + + @Override + public BookPath as(String alias) { + return new BookPath(DSL.name(alias), this); + } + + @Override + public BookPath as(Name alias) { + return new BookPath(alias, this); + } + + @Override + public BookPath as(Table alias) { + return new BookPath(alias.getQualifiedName(), this); + } + } + + @Override + public Schema getSchema() { + return aliased() ? null : Public.PUBLIC; + } + + @Override + public List getIndexes() { + return Arrays.asList(Indexes.BOOK_AUTHOR_IDX); + } + + @Override + public Identity getIdentity() { + return (Identity) super.getIdentity(); + } + + @Override + public UniqueKey getPrimaryKey() { + return Keys.BOOK_PKEY; + } + + @Override + public List> getUniqueKeys() { + return Arrays.asList(Keys.BOOK_ISBN_KEY); + } + + @Override + public List> getReferences() { + return Arrays.asList(Keys.BOOK__BOOK_AUTHOR_ID_FKEY); + } + + private transient AuthorPath _author; + + /** + * Get the implicit join path to the public.author table. + */ + public AuthorPath author() { + if (_author == null) + _author = new AuthorPath(this, Keys.BOOK__BOOK_AUTHOR_ID_FKEY, null); + + return _author; + } + + private transient ReviewPath _review; + + /** + * Get the implicit to-many join path to the public.review + * table + */ + public ReviewPath review() { + if (_review == null) + _review = new ReviewPath(this, null, Keys.REVIEW__REVIEW_BOOK_ID_FKEY.getInverseKey()); + + return _review; + } + + @Override + public List> getChecks() { + return Arrays.asList( + Internal.createCheck(this, DSL.name("book_price_check"), "((price >= (0)::numeric))", true) + ); + } + + @Override + public Book as(String alias) { + return new Book(DSL.name(alias), this); + } + + @Override + public Book as(Name alias) { + return new Book(alias, this); + } + + @Override + public Book as(Table alias) { + return new Book(alias.getQualifiedName(), this); + } + + /** + * Rename this table + */ + @Override + public Book rename(String name) { + return new Book(DSL.name(name), null); + } + + /** + * Rename this table + */ + @Override + public Book rename(Name name) { + return new Book(name, null); + } + + /** + * Rename this table + */ + @Override + public Book rename(Table name) { + return new Book(name.getQualifiedName(), null); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Book where(Condition condition) { + return new Book(getQualifiedName(), aliased() ? this : null, null, Internal.condition(this, condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Book where(Collection conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Book where(Condition... conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Book where(Field condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Book where(SQL condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Book where(@Stringly.SQL String condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Book where(@Stringly.SQL String condition, Object... binds) { + return where(DSL.condition(condition, binds)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Book where(@Stringly.SQL String condition, QueryPart... parts) { + return where(DSL.condition(condition, parts)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Book whereExists(TableLike select) { + return where(DSL.exists(select)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Book whereNotExists(TableLike select) { + return where(DSL.notExists(select)); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/Review.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/Review.java new file mode 100644 index 0000000..e1ff158 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/Review.java @@ -0,0 +1,318 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables; + + +import com.ankurm.jooq.generated.Indexes; +import com.ankurm.jooq.generated.Keys; +import com.ankurm.jooq.generated.Public; +import com.ankurm.jooq.generated.tables.Book.BookPath; +import com.ankurm.jooq.generated.tables.records.ReviewRecord; + +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.jooq.Check; +import org.jooq.Condition; +import org.jooq.Field; +import org.jooq.ForeignKey; +import org.jooq.Identity; +import org.jooq.Index; +import org.jooq.InverseForeignKey; +import org.jooq.Name; +import org.jooq.Path; +import org.jooq.PlainSQL; +import org.jooq.QueryPart; +import org.jooq.Record; +import org.jooq.SQL; +import org.jooq.Schema; +import org.jooq.Stringly; +import org.jooq.Table; +import org.jooq.TableField; +import org.jooq.TableLike; +import org.jooq.TableOptions; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; +import org.jooq.impl.SQLDataType; +import org.jooq.impl.TableImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class Review extends TableImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of public.review + */ + public static final Review REVIEW = new Review(); + + /** + * The class holding records for this type + */ + @Override + public Class getRecordType() { + return ReviewRecord.class; + } + + /** + * The column public.review.id. + */ + public final TableField ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).generatedAlwaysAsIdentity(), this, ""); + + /** + * The column public.review.book_id. + */ + public final TableField BOOK_ID = createField(DSL.name("book_id"), SQLDataType.BIGINT.nullable(false), this, ""); + + /** + * The column public.review.rating. + */ + public final TableField RATING = createField(DSL.name("rating"), SQLDataType.SMALLINT.nullable(false), this, ""); + + /** + * The column public.review.body. + */ + public final TableField BODY = createField(DSL.name("body"), SQLDataType.CLOB, this, ""); + + /** + * The column public.review.created_at. + */ + public final TableField CREATED_AT = createField(DSL.name("created_at"), SQLDataType.TIMESTAMPWITHTIMEZONE(6).nullable(false).defaultValue(DSL.field(DSL.raw("now()"), SQLDataType.TIMESTAMPWITHTIMEZONE)), this, ""); + + private Review(Name alias, Table aliased) { + this(alias, aliased, (Field[]) null, null); + } + + private Review(Name alias, Table aliased, Field[] parameters, Condition where) { + super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table(), where); + } + + /** + * Create an aliased public.review table reference + */ + public Review(String alias) { + this(DSL.name(alias), REVIEW); + } + + /** + * Create an aliased public.review table reference + */ + public Review(Name alias) { + this(alias, REVIEW); + } + + /** + * Create a public.review table reference + */ + public Review() { + this(DSL.name("review"), null); + } + + public Review(Table path, ForeignKey childPath, InverseForeignKey parentPath) { + super(path, childPath, parentPath, REVIEW); + } + + /** + * A subtype implementing {@link Path} for simplified path-based joins. + */ + public static class ReviewPath extends Review implements Path { + + private static final long serialVersionUID = 1L; + public ReviewPath(Table path, ForeignKey childPath, InverseForeignKey parentPath) { + super(path, childPath, parentPath); + } + private ReviewPath(Name alias, Table aliased) { + super(alias, aliased); + } + + @Override + public ReviewPath as(String alias) { + return new ReviewPath(DSL.name(alias), this); + } + + @Override + public ReviewPath as(Name alias) { + return new ReviewPath(alias, this); + } + + @Override + public ReviewPath as(Table alias) { + return new ReviewPath(alias.getQualifiedName(), this); + } + } + + @Override + public Schema getSchema() { + return aliased() ? null : Public.PUBLIC; + } + + @Override + public List getIndexes() { + return Arrays.asList(Indexes.REVIEW_BOOK_IDX); + } + + @Override + public Identity getIdentity() { + return (Identity) super.getIdentity(); + } + + @Override + public UniqueKey getPrimaryKey() { + return Keys.REVIEW_PKEY; + } + + @Override + public List> getReferences() { + return Arrays.asList(Keys.REVIEW__REVIEW_BOOK_ID_FKEY); + } + + private transient BookPath _book; + + /** + * Get the implicit join path to the public.book table. + */ + public BookPath book() { + if (_book == null) + _book = new BookPath(this, Keys.REVIEW__REVIEW_BOOK_ID_FKEY, null); + + return _book; + } + + @Override + public List> getChecks() { + return Arrays.asList( + Internal.createCheck(this, DSL.name("review_rating_check"), "(((rating >= 1) AND (rating <= 5)))", true) + ); + } + + @Override + public Review as(String alias) { + return new Review(DSL.name(alias), this); + } + + @Override + public Review as(Name alias) { + return new Review(alias, this); + } + + @Override + public Review as(Table alias) { + return new Review(alias.getQualifiedName(), this); + } + + /** + * Rename this table + */ + @Override + public Review rename(String name) { + return new Review(DSL.name(name), null); + } + + /** + * Rename this table + */ + @Override + public Review rename(Name name) { + return new Review(name, null); + } + + /** + * Rename this table + */ + @Override + public Review rename(Table name) { + return new Review(name.getQualifiedName(), null); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Review where(Condition condition) { + return new Review(getQualifiedName(), aliased() ? this : null, null, Internal.condition(this, condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Review where(Collection conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Review where(Condition... conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Review where(Field condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Review where(SQL condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Review where(@Stringly.SQL String condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Review where(@Stringly.SQL String condition, Object... binds) { + return where(DSL.condition(condition, binds)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public Review where(@Stringly.SQL String condition, QueryPart... parts) { + return where(DSL.condition(condition, parts)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Review whereExists(TableLike select) { + return where(DSL.exists(select)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public Review whereNotExists(TableLike select) { + return where(DSL.notExists(select)); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Author.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Author.java new file mode 100644 index 0000000..d5978c0 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Author.java @@ -0,0 +1,82 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables.pojos; + + +import java.io.Serializable; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public record Author( + Long id, + String name, + String country +) implements Serializable { + + private static final long serialVersionUID = 1L; + + + public Author(Author value) { + this( + value.id, + value.name, + value.country + ); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Author other = (Author) obj; + if (this.id == null) { + if (other.id != null) + return false; + } + else if (!this.id.equals(other.id)) + return false; + if (this.name == null) { + if (other.name != null) + return false; + } + else if (!this.name.equals(other.name)) + return false; + if (this.country == null) { + if (other.country != null) + return false; + } + else if (!this.country.equals(other.country)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.id == null) ? 0 : this.id.hashCode()); + result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); + result = prime * result + ((this.country == null) ? 0 : this.country.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Author ("); + + sb.append(id); + sb.append(", ").append(name); + sb.append(", ").append(country); + + sb.append(")"); + return sb.toString(); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Book.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Book.java new file mode 100644 index 0000000..82189ee --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Book.java @@ -0,0 +1,136 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables.pojos; + + +import com.ankurm.jooq.generated.enums.Genre; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.time.LocalDate; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public record Book( + Long id, + Long authorId, + String title, + Genre genre, + BigDecimal price, + LocalDate publishedOn, + Integer stock, + String isbn +) implements Serializable { + + private static final long serialVersionUID = 1L; + + + public Book(Book value) { + this( + value.id, + value.authorId, + value.title, + value.genre, + value.price, + value.publishedOn, + value.stock, + value.isbn + ); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Book other = (Book) obj; + if (this.id == null) { + if (other.id != null) + return false; + } + else if (!this.id.equals(other.id)) + return false; + if (this.authorId == null) { + if (other.authorId != null) + return false; + } + else if (!this.authorId.equals(other.authorId)) + return false; + if (this.title == null) { + if (other.title != null) + return false; + } + else if (!this.title.equals(other.title)) + return false; + if (this.genre == null) { + if (other.genre != null) + return false; + } + else if (!this.genre.equals(other.genre)) + return false; + if (this.price == null) { + if (other.price != null) + return false; + } + else if (!this.price.equals(other.price)) + return false; + if (this.publishedOn == null) { + if (other.publishedOn != null) + return false; + } + else if (!this.publishedOn.equals(other.publishedOn)) + return false; + if (this.stock == null) { + if (other.stock != null) + return false; + } + else if (!this.stock.equals(other.stock)) + return false; + if (this.isbn == null) { + if (other.isbn != null) + return false; + } + else if (!this.isbn.equals(other.isbn)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.id == null) ? 0 : this.id.hashCode()); + result = prime * result + ((this.authorId == null) ? 0 : this.authorId.hashCode()); + result = prime * result + ((this.title == null) ? 0 : this.title.hashCode()); + result = prime * result + ((this.genre == null) ? 0 : this.genre.hashCode()); + result = prime * result + ((this.price == null) ? 0 : this.price.hashCode()); + result = prime * result + ((this.publishedOn == null) ? 0 : this.publishedOn.hashCode()); + result = prime * result + ((this.stock == null) ? 0 : this.stock.hashCode()); + result = prime * result + ((this.isbn == null) ? 0 : this.isbn.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Book ("); + + sb.append(id); + sb.append(", ").append(authorId); + sb.append(", ").append(title); + sb.append(", ").append(genre); + sb.append(", ").append(price); + sb.append(", ").append(publishedOn); + sb.append(", ").append(stock); + sb.append(", ").append(isbn); + + sb.append(")"); + return sb.toString(); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Review.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Review.java new file mode 100644 index 0000000..9da159e --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/pojos/Review.java @@ -0,0 +1,103 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables.pojos; + + +import java.io.Serializable; +import java.time.OffsetDateTime; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public record Review( + Long id, + Long bookId, + Short rating, + String body, + OffsetDateTime createdAt +) implements Serializable { + + private static final long serialVersionUID = 1L; + + + public Review(Review value) { + this( + value.id, + value.bookId, + value.rating, + value.body, + value.createdAt + ); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Review other = (Review) obj; + if (this.id == null) { + if (other.id != null) + return false; + } + else if (!this.id.equals(other.id)) + return false; + if (this.bookId == null) { + if (other.bookId != null) + return false; + } + else if (!this.bookId.equals(other.bookId)) + return false; + if (this.rating == null) { + if (other.rating != null) + return false; + } + else if (!this.rating.equals(other.rating)) + return false; + if (this.body == null) { + if (other.body != null) + return false; + } + else if (!this.body.equals(other.body)) + return false; + if (this.createdAt == null) { + if (other.createdAt != null) + return false; + } + else if (!this.createdAt.equals(other.createdAt)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.id == null) ? 0 : this.id.hashCode()); + result = prime * result + ((this.bookId == null) ? 0 : this.bookId.hashCode()); + result = prime * result + ((this.rating == null) ? 0 : this.rating.hashCode()); + result = prime * result + ((this.body == null) ? 0 : this.body.hashCode()); + result = prime * result + ((this.createdAt == null) ? 0 : this.createdAt.hashCode()); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("Review ("); + + sb.append(id); + sb.append(", ").append(bookId); + sb.append(", ").append(rating); + sb.append(", ").append(body); + sb.append(", ").append(createdAt); + + sb.append(")"); + return sb.toString(); + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/AuthorRecord.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/AuthorRecord.java new file mode 100644 index 0000000..2d16594 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/AuthorRecord.java @@ -0,0 +1,108 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables.records; + + +import com.ankurm.jooq.generated.tables.Author; + +import org.jooq.Record1; +import org.jooq.impl.UpdatableRecordImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class AuthorRecord extends UpdatableRecordImpl { + + private static final long serialVersionUID = 1L; + + /** + * Setter for public.author.id. + */ + public void setId(Long value) { + set(0, value); + } + + /** + * Getter for public.author.id. + */ + public Long getId() { + return (Long) get(0); + } + + /** + * Setter for public.author.name. + */ + public void setName(String value) { + set(1, value); + } + + /** + * Getter for public.author.name. + */ + public String getName() { + return (String) get(1); + } + + /** + * Setter for public.author.country. + */ + public void setCountry(String value) { + set(2, value); + } + + /** + * Getter for public.author.country. + */ + public String getCountry() { + return (String) get(2); + } + + // ------------------------------------------------------------------------- + // Primary key information + // ------------------------------------------------------------------------- + + @Override + public Record1 key() { + return (Record1) super.key(); + } + + // ------------------------------------------------------------------------- + // Constructors + // ------------------------------------------------------------------------- + + /** + * Create a detached AuthorRecord + */ + public AuthorRecord() { + super(Author.AUTHOR); + } + + /** + * Create a detached, initialised AuthorRecord + */ + public AuthorRecord(Long id, String name, String country) { + super(Author.AUTHOR); + + setId(id); + setName(name); + setCountry(country); + resetTouchedOnNotNull(); + } + + /** + * Create a detached, initialised AuthorRecord + */ + public AuthorRecord(com.ankurm.jooq.generated.tables.pojos.Author value) { + super(Author.AUTHOR); + + if (value != null) { + setId(value.id()); + setName(value.name()); + setCountry(value.country()); + resetTouchedOnNotNull(); + } + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/BookRecord.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/BookRecord.java new file mode 100644 index 0000000..47e620e --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/BookRecord.java @@ -0,0 +1,192 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables.records; + + +import com.ankurm.jooq.generated.enums.Genre; +import com.ankurm.jooq.generated.tables.Book; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import org.jooq.Record1; +import org.jooq.impl.UpdatableRecordImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class BookRecord extends UpdatableRecordImpl { + + private static final long serialVersionUID = 1L; + + /** + * Setter for public.book.id. + */ + public void setId(Long value) { + set(0, value); + } + + /** + * Getter for public.book.id. + */ + public Long getId() { + return (Long) get(0); + } + + /** + * Setter for public.book.author_id. + */ + public void setAuthorId(Long value) { + set(1, value); + } + + /** + * Getter for public.book.author_id. + */ + public Long getAuthorId() { + return (Long) get(1); + } + + /** + * Setter for public.book.title. + */ + public void setTitle(String value) { + set(2, value); + } + + /** + * Getter for public.book.title. + */ + public String getTitle() { + return (String) get(2); + } + + /** + * Setter for public.book.genre. + */ + public void setGenre(Genre value) { + set(3, value); + } + + /** + * Getter for public.book.genre. + */ + public Genre getGenre() { + return (Genre) get(3); + } + + /** + * Setter for public.book.price. + */ + public void setPrice(BigDecimal value) { + set(4, value); + } + + /** + * Getter for public.book.price. + */ + public BigDecimal getPrice() { + return (BigDecimal) get(4); + } + + /** + * Setter for public.book.published_on. + */ + public void setPublishedOn(LocalDate value) { + set(5, value); + } + + /** + * Getter for public.book.published_on. + */ + public LocalDate getPublishedOn() { + return (LocalDate) get(5); + } + + /** + * Setter for public.book.stock. + */ + public void setStock(Integer value) { + set(6, value); + } + + /** + * Getter for public.book.stock. + */ + public Integer getStock() { + return (Integer) get(6); + } + + /** + * Setter for public.book.isbn. + */ + public void setIsbn(String value) { + set(7, value); + } + + /** + * Getter for public.book.isbn. + */ + public String getIsbn() { + return (String) get(7); + } + + // ------------------------------------------------------------------------- + // Primary key information + // ------------------------------------------------------------------------- + + @Override + public Record1 key() { + return (Record1) super.key(); + } + + // ------------------------------------------------------------------------- + // Constructors + // ------------------------------------------------------------------------- + + /** + * Create a detached BookRecord + */ + public BookRecord() { + super(Book.BOOK); + } + + /** + * Create a detached, initialised BookRecord + */ + public BookRecord(Long id, Long authorId, String title, Genre genre, BigDecimal price, LocalDate publishedOn, Integer stock, String isbn) { + super(Book.BOOK); + + setId(id); + setAuthorId(authorId); + setTitle(title); + setGenre(genre); + setPrice(price); + setPublishedOn(publishedOn); + setStock(stock); + setIsbn(isbn); + resetTouchedOnNotNull(); + } + + /** + * Create a detached, initialised BookRecord + */ + public BookRecord(com.ankurm.jooq.generated.tables.pojos.Book value) { + super(Book.BOOK); + + if (value != null) { + setId(value.id()); + setAuthorId(value.authorId()); + setTitle(value.title()); + setGenre(value.genre()); + setPrice(value.price()); + setPublishedOn(value.publishedOn()); + setStock(value.stock()); + setIsbn(value.isbn()); + resetTouchedOnNotNull(); + } + } +} diff --git a/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/ReviewRecord.java b/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/ReviewRecord.java new file mode 100644 index 0000000..5c128a0 --- /dev/null +++ b/jooq/src/main/java/com/ankurm/jooq/generated/tables/records/ReviewRecord.java @@ -0,0 +1,142 @@ +/* + * This file is generated by jOOQ. + */ +package com.ankurm.jooq.generated.tables.records; + + +import com.ankurm.jooq.generated.tables.Review; + +import java.time.OffsetDateTime; + +import org.jooq.Record1; +import org.jooq.impl.UpdatableRecordImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class ReviewRecord extends UpdatableRecordImpl { + + private static final long serialVersionUID = 1L; + + /** + * Setter for public.review.id. + */ + public void setId(Long value) { + set(0, value); + } + + /** + * Getter for public.review.id. + */ + public Long getId() { + return (Long) get(0); + } + + /** + * Setter for public.review.book_id. + */ + public void setBookId(Long value) { + set(1, value); + } + + /** + * Getter for public.review.book_id. + */ + public Long getBookId() { + return (Long) get(1); + } + + /** + * Setter for public.review.rating. + */ + public void setRating(Short value) { + set(2, value); + } + + /** + * Getter for public.review.rating. + */ + public Short getRating() { + return (Short) get(2); + } + + /** + * Setter for public.review.body. + */ + public void setBody(String value) { + set(3, value); + } + + /** + * Getter for public.review.body. + */ + public String getBody() { + return (String) get(3); + } + + /** + * Setter for public.review.created_at. + */ + public void setCreatedAt(OffsetDateTime value) { + set(4, value); + } + + /** + * Getter for public.review.created_at. + */ + public OffsetDateTime getCreatedAt() { + return (OffsetDateTime) get(4); + } + + // ------------------------------------------------------------------------- + // Primary key information + // ------------------------------------------------------------------------- + + @Override + public Record1 key() { + return (Record1) super.key(); + } + + // ------------------------------------------------------------------------- + // Constructors + // ------------------------------------------------------------------------- + + /** + * Create a detached ReviewRecord + */ + public ReviewRecord() { + super(Review.REVIEW); + } + + /** + * Create a detached, initialised ReviewRecord + */ + public ReviewRecord(Long id, Long bookId, Short rating, String body, OffsetDateTime createdAt) { + super(Review.REVIEW); + + setId(id); + setBookId(bookId); + setRating(rating); + setBody(body); + setCreatedAt(createdAt); + resetTouchedOnNotNull(); + } + + /** + * Create a detached, initialised ReviewRecord + */ + public ReviewRecord(com.ankurm.jooq.generated.tables.pojos.Review value) { + super(Review.REVIEW); + + if (value != null) { + setId(value.id()); + setBookId(value.bookId()); + setRating(value.rating()); + setBody(value.body()); + setCreatedAt(value.createdAt()); + resetTouchedOnNotNull(); + } + } +} diff --git a/jooq/src/main/resources/application.properties b/jooq/src/main/resources/application.properties new file mode 100644 index 0000000..2506fce --- /dev/null +++ b/jooq/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.application.name=jooq-demo +# Flyway runs the migrations at startup; jOOQ's generated classes were produced from the same files. +spring.flyway.locations=classpath:db/migration diff --git a/jooq/src/main/resources/db/migration/V1__bookshop.sql b/jooq/src/main/resources/db/migration/V1__bookshop.sql new file mode 100644 index 0000000..755bd75 --- /dev/null +++ b/jooq/src/main/resources/db/migration/V1__bookshop.sql @@ -0,0 +1,27 @@ +CREATE TYPE genre AS ENUM ('FICTION', 'SCIENCE', 'HISTORY', 'TECH'); + +CREATE TABLE author ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + name TEXT NOT NULL, + country CHAR(2) NOT NULL +); + +CREATE TABLE book ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + author_id BIGINT NOT NULL REFERENCES author (id), + title TEXT NOT NULL, + genre genre NOT NULL, + price NUMERIC(10, 2) NOT NULL CHECK (price >= 0), + published_on DATE NOT NULL, + stock INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX book_author_idx ON book (author_id); + +CREATE TABLE review ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + book_id BIGINT NOT NULL REFERENCES book (id), + rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5), + body TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX review_book_idx ON review (book_id); diff --git a/jooq/src/main/resources/db/migration/V2__book_isbn.sql b/jooq/src/main/resources/db/migration/V2__book_isbn.sql new file mode 100644 index 0000000..1e3e011 --- /dev/null +++ b/jooq/src/main/resources/db/migration/V2__book_isbn.sql @@ -0,0 +1,5 @@ +-- A schema change after the first codegen run: this is the migration that makes the compiler useful. +ALTER TABLE book ADD COLUMN isbn TEXT; +UPDATE book SET isbn = 'legacy-' || id WHERE isbn IS NULL; +ALTER TABLE book ALTER COLUMN isbn SET NOT NULL; +ALTER TABLE book ADD CONSTRAINT book_isbn_key UNIQUE (isbn); diff --git a/jooq/src/test/java/com/ankurm/jooq/CodegenDriftTest.java b/jooq/src/test/java/com/ankurm/jooq/CodegenDriftTest.java new file mode 100644 index 0000000..361f80f --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/CodegenDriftTest.java @@ -0,0 +1,75 @@ +package com.ankurm.jooq; + +import org.jooq.codegen.GenerationTool; +import org.jooq.meta.jaxb.*; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; +import java.io.IOException; +import java.nio.file.*; +import java.sql.Connection; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Regenerates the jOOQ classes from the database that Flyway just migrated (a real PostgreSQL 17 in + * Testcontainers) and compares them, file by file, with the classes committed under src/main/java. + * If someone adds a migration and forgets to regenerate, this test fails. + */ +class CodegenDriftTest extends PostgresTestBase { + + @Autowired DataSource dataSource; + + @Test + void committedGeneratedCodeMatchesMigrations() throws Exception { + Transcript t = new Transcript("01-codegen-drift-check.txt"); + Path tmp = Files.createTempDirectory("jooq-regen"); + + Configuration cfg = new Configuration() + .withJdbc(new Jdbc() + .withDriver("org.postgresql.Driver") + .withUrl(postgres.getJdbcUrl()) + .withUser(postgres.getUsername()) + .withPassword(postgres.getPassword())) + .withGenerator(new Generator() + .withDatabase(new Database() + .withName("org.jooq.meta.postgres.PostgresDatabase") + .withInputSchema("public") + .withExcludes("flyway_schema_history")) + .withGenerate(new Generate() + .withPojos(true).withPojosAsJavaRecordClasses(true) + .withDaos(false).withGeneratedAnnotation(false).withDeprecated(false)) + .withTarget(new Target() + .withPackageName("com.ankurm.jooq.generated") + .withDirectory(tmp.toString()))); + GenerationTool.generate(cfg); + + Path fresh = tmp.resolve("com/ankurm/jooq/generated"); + Path committed = Path.of("src/main/java/com/ankurm/jooq/generated"); + List freshFiles = list(fresh); + List committedFiles = list(committed); + + t.line("files regenerated from the live schema: %d", freshFiles.size()); + t.line("files committed in src/main/java: %d", committedFiles.size()); + assertEquals(committedFiles, freshFiles, "set of generated files differs"); + + List stale = freshFiles.stream().filter(rel -> { + try { + return !Files.readString(committed.resolve(rel)).equals(Files.readString(fresh.resolve(rel))); + } catch (IOException e) { throw new RuntimeException(e); } + }).toList(); + assertTrue(stale.isEmpty(), "generated code is stale, run scripts/codegen.sh. Differing files: " + stale); + t.line("byte-identical files: %d", freshFiles.size()); + t.line("verdict: committed generated code matches Flyway V1 + V2"); + t.write(); + } + + private static List list(Path root) throws IOException { + try (Stream s = Files.walk(root)) { + return s.filter(Files::isRegularFile).map(root::relativize).sorted().toList(); + } + } +} diff --git a/jooq/src/test/java/com/ankurm/jooq/IgnoredListener.java b/jooq/src/test/java/com/ankurm/jooq/IgnoredListener.java new file mode 100644 index 0000000..2bd8991 --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/IgnoredListener.java @@ -0,0 +1,18 @@ +package com.ankurm.jooq; + +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListener; +import org.springframework.stereotype.Component; + +import java.util.concurrent.atomic.AtomicInteger; + +/** A plain ExecuteListener bean, to show that Spring Boot does not register it. */ +@Component +class IgnoredListener implements ExecuteListener { + static final AtomicInteger calls = new AtomicInteger(); + + @Override + public void renderEnd(ExecuteContext ctx) { + calls.incrementAndGet(); + } +} diff --git a/jooq/src/test/java/com/ankurm/jooq/JooqSliceTest.java b/jooq/src/test/java/com/ankurm/jooq/JooqSliceTest.java new file mode 100644 index 0000000..c859f52 --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/JooqSliceTest.java @@ -0,0 +1,39 @@ +package com.ankurm.jooq; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.jooq.test.autoconfigure.JooqTest; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.TestPropertySource; +import org.testcontainers.postgresql.PostgreSQLContainer; + +import static com.ankurm.jooq.generated.Tables.AUTHOR; +import static org.junit.jupiter.api.Assertions.*; + +/** The @JooqTest slice: only jOOQ + DataSource auto-configuration, no @Component/@Repository/@Service beans. */ +@JooqTest +@TestPropertySource(properties = "spring.test.database.replace=none") +class JooqSliceTest { + + @ServiceConnection + static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine"); + static { postgres.start(); } + + @Autowired DSLContext dsl; + @Autowired ApplicationContext ctx; + + @Test + void sliceContents() { + Transcript t = new Transcript("12-jooqtest-slice.txt"); + t.line("DSLContext present: %s (dialect %s)", dsl != null, dsl.dialect()); + t.line("BookshopRepository in context: %s", ctx.getBeanNamesForType(BookshopRepository.class).length > 0); + t.line("StockService in context: %s", ctx.getBeanNamesForType(StockService.class).length > 0); + t.line("SqlLog in context: %s", ctx.getBeanNamesForType(SqlLog.class).length > 0); + t.line("Flyway ran (schema has tables): %s", dsl.fetchOne("select to_regclass('public.book') is not null as present").get("present")); + assertFalse(ctx.getBeanNamesForType(BookshopRepository.class).length > 0); + t.line("author rows via typed API: %d", dsl.fetchCount(AUTHOR)); + t.write(); + } +} diff --git a/jooq/src/test/java/com/ankurm/jooq/PostgresTestBase.java b/jooq/src/test/java/com/ankurm/jooq/PostgresTestBase.java new file mode 100644 index 0000000..6ef1c5f --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/PostgresTestBase.java @@ -0,0 +1,70 @@ +package com.ankurm.jooq; + +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.testcontainers.postgresql.PostgreSQLContainer; +import org.junit.jupiter.api.BeforeEach; + +import java.util.List; +import java.util.function.Supplier; + +import static com.ankurm.jooq.generated.Tables.*; + +/** + * One real PostgreSQL 17 for the whole test run; Flyway migrates it when the Spring context starts. + * + * The container is a started-once singleton, NOT a per-class @Container. Spring caches the + * ApplicationContext across test classes, so a per-class container is stopped after the first + * class while the cached context keeps pointing at it (output/09-container-lifecycle-trap.txt). + */ +@SpringBootTest +abstract class PostgresTestBase { + + @ServiceConnection + static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine"); + + static { + postgres.start(); + } + + @Autowired DSLContext dsl; + @Autowired BookshopRepository repo; + @Autowired SqlLog sqlLog; + + /** Seed ids, filled by seed(). */ + long ada, grace, kenji; + + @BeforeEach + void seed() { + dsl.execute("TRUNCATE review, book, author RESTART IDENTITY CASCADE"); + ada = repo.insertAuthor("Ada Lovelace", "GB"); + grace = repo.insertAuthor("Grace Hopper", "US"); + kenji = repo.insertAuthor("Kenji Tanaka", "JP"); + var b1 = repo.insertBook(ada, "Notes on the Analytical Engine", com.ankurm.jooq.generated.enums.Genre.SCIENCE, "24.50", "2020-03-01", 10, "978-0-01"); + var b2 = repo.insertBook(ada, "Poetical Science", com.ankurm.jooq.generated.enums.Genre.FICTION, "12.00", "2021-06-15", 5, "978-0-02"); + var b3 = repo.insertBook(grace, "Compilers for Humans", com.ankurm.jooq.generated.enums.Genre.TECH, "45.00", "2022-01-10", 7, "978-0-03"); + var b4 = repo.insertBook(grace, "Debugging a Moth", com.ankurm.jooq.generated.enums.Genre.HISTORY, "18.75", "2023-09-09", 0, "978-0-04"); + var b5 = repo.insertBook(kenji, "Kata of Clean Code", com.ankurm.jooq.generated.enums.Genre.TECH, "39.90", "2024-02-02", 12, "978-0-05"); + var b6 = repo.insertBook(kenji, "Tokyo Trains", com.ankurm.jooq.generated.enums.Genre.HISTORY, "22.00", "2025-05-05", 3, "978-0-06"); + repo.addReview(b1.id(), 5, "Foundational"); + repo.addReview(b1.id(), 4, "Dense but worth it"); + repo.addReview(b2.id(), 3, "Charming"); + repo.addReview(b3.id(), 5, "Changed how I think"); + repo.addReview(b3.id(), 4, "Great examples"); + repo.addReview(b3.id(), 5, "Buy it"); + repo.addReview(b5.id(), 2, "Too many koans"); + repo.addReview(b6.id(), 4, "Lovely photographs"); + sqlLog.clear(); + } + + /** Runs the block and returns the SQL jOOQ rendered while it ran. */ + Captured capture(Supplier block) { + sqlLog.clear(); + T result = block.get(); + return new Captured<>(result, sqlLog.statements()); + } + + record Captured(T result, List sql) {} +} diff --git a/jooq/src/test/java/com/ankurm/jooq/QueryTests.java b/jooq/src/test/java/com/ankurm/jooq/QueryTests.java new file mode 100644 index 0000000..2061d9e --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/QueryTests.java @@ -0,0 +1,141 @@ +package com.ankurm.jooq; + +import com.ankurm.jooq.Views.*; +import com.ankurm.jooq.generated.enums.Genre; +import com.ankurm.jooq.generated.tables.pojos.Book; +import org.springframework.dao.DataAccessException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.util.List; + +import static com.ankurm.jooq.generated.Tables.*; +import static org.junit.jupiter.api.Assertions.*; + +class QueryTests extends PostgresTestBase { + + @Autowired ApplicationContext ctx; + + private static String rootMessage(Throwable e) { + while (e.getCause() != null) e = e.getCause(); + return e.getMessage().lines().findFirst().orElse(""); + } + + @Test + void autoconfigAndInsertReturning() { + Transcript t = new Transcript("02-autoconfig-and-insert-returning.txt"); + t.line("DSLContext dialect: %s", dsl.dialect()); + t.line("Flyway history: %s", dsl.fetch("select version, description, success from flyway_schema_history order by installed_rank") + .map(r -> r.get("version") + " " + r.get("description") + " success=" + r.get("success"))); + assertEquals("POSTGRES", dsl.dialect().name()); + t.line("listener providers on the DSLContext: %s", dsl.configuration().executeListenerProviders().length); + t.line("transaction provider: %s", dsl.configuration().transactionProvider().getClass().getName()); + t.line("plain ExecuteListener bean calls so far: %d (bean exists: %s)", IgnoredListener.calls.get(), ctx.getBeansOfType(IgnoredListener.class).size() == 1); + assertEquals(0, IgnoredListener.calls.get()); + + var cap = capture(() -> repo.insertBook(ada, "Returning Demo", Genre.TECH, "10.50", "2026-02-02", 1, "978-9-99")); + Book b = cap.result(); + t.line(""); + t.line("SQL: %s", cap.sql().getFirst()); + t.line("Returned POJO (a generated Java record): %s", b); + assertNotNull(b.id()); + assertEquals(1, cap.sql().size()); + + // the column is GENERATED ALWAYS AS IDENTITY: setting it is rejected by PostgreSQL + DataAccessException e = assertThrows(DataAccessException.class, () -> + dsl.insertInto(AUTHOR).set(AUTHOR.ID, 999L).set(AUTHOR.NAME, "x").set(AUTHOR.COUNTRY, "US").execute()); + t.line(""); + t.line("insert with explicit id on GENERATED ALWAYS column: %s", rootMessage(e)); + t.write(); + } + + @Test + void dynamicSearch() { + Transcript t = new Transcript("03-dynamic-where.txt"); + var none = capture(() -> repo.search(new BookFilter(null, null, null, null))); + var tech = capture(() -> repo.search(new BookFilter(null, Genre.TECH, null, null))); + var all = capture(() -> repo.search(new BookFilter("c", Genre.TECH, new BigDecimal("40.00"), "JP"))); + + for (var c : List.of(none, tech, all)) { + t.line("SQL: %s", c.sql().getFirst()); + c.result().forEach(r -> t.line(" row: %s", r)); + t.line(""); + } + assertEquals(6, none.result().size()); + assertEquals(2, tech.result().size()); + assertEquals(1, all.result().size()); + assertFalse(none.sql().getFirst().contains("where")); + t.write(); + } + + @Test + void multisetVersusJoin() { + Transcript t = new Transcript("04-multiset.txt"); + var cap = capture(repo::booksWithReviews); + t.line("statements sent: %d", cap.sql().size()); + t.line("SQL: %s", cap.sql().getFirst()); + t.line(""); + cap.result().forEach(b -> t.line("%s", b)); + + // the same data as a flat join: parent columns repeat once per child + var flat = dsl.select(BOOK.TITLE, REVIEW.RATING).from(BOOK).leftJoin(REVIEW).on(REVIEW.BOOK_ID.eq(BOOK.ID)).fetch(); + t.line(""); + t.line("flat LEFT JOIN returns %d rows for %d books; MULTISET returns %d rows", flat.size(), repo.countBooks(), cap.result().size()); + assertEquals(1, cap.sql().size()); + assertEquals(6, cap.result().size()); + assertEquals(3, cap.result().stream().filter(b -> b.title().equals("Compilers for Humans")).findFirst().orElseThrow().reviews().size()); + assertEquals(9, flat.size()); + t.write(); + } + + @Test + void cteAndWindowFunction() { + Transcript t = new Transcript("05-cte-window.txt"); + var cap = capture(repo::topRatedPerGenre); + t.line("SQL: %s", cap.sql().getFirst()); + t.line(""); + cap.result().forEach(r -> t.line("%s", r)); + var board = capture(repo::authorLeaderboard); + t.line(""); + t.line("SQL: %s", board.sql().getFirst()); + board.result().forEach(r -> t.line("%s", r)); + assertEquals(4, cap.result().size()); // FICTION, SCIENCE, HISTORY, TECH all have a reviewed book + t.write(); + } + + @Test + void upsertAndKeyset() { + Transcript t = new Transcript("06-upsert-and-keyset.txt"); + var first = capture(() -> repo.upsertByIsbn(ada, "ISBN-UP", "Upsert Book", 4)); + var second = capture(() -> repo.upsertByIsbn(ada, "ISBN-UP", "Upsert Book", 4)); + t.line("SQL: %s", first.sql().getFirst()); + t.line("first call -> stock %d (inserted)", first.result().stock()); + t.line("second call -> stock %d (conflict, stock added); same id: %s", second.result().stock(), first.result().id().equals(second.result().id())); + assertEquals(4, first.result().stock()); + assertEquals(8, second.result().stock()); + + t.line(""); + var p1 = capture(() -> repo.pageAfter(null, 3)); + var p2 = capture(() -> repo.pageAfter(p1.result().next(), 3)); + t.line("page 1 SQL: %s", p1.sql().getFirst()); + t.line("page 1: %s next=%s", p1.result().ids(), p1.result().next()); + t.line("page 2 SQL: %s", p2.sql().getFirst()); + t.line("page 2: %s next=%s", p2.result().ids(), p2.result().next()); + assertEquals(List.of(1L, 2L, 3L), p1.result().ids()); + assertEquals(List.of(4L, 5L, 6L), p2.result().ids()); + t.write(); + } + + @Test + void stringSqlFailsAtRuntimeTypedSqlFailsAtCompileTime() { + Transcript t = new Transcript("07-runtime-failure-of-plain-sql.txt"); + DataAccessException e = assertThrows(DataAccessException.class, () -> dsl.fetch("select isbnn from book")); + t.line("dsl.fetch(\"select isbnn from book\") compiles fine and fails at runtime:"); + t.line(" exception type: %s", e.getClass().getName()); + t.line(" root cause: %s", rootMessage(e)); + assertTrue(rootMessage(e).contains("isbnn")); + t.write(); + } +} diff --git a/jooq/src/test/java/com/ankurm/jooq/TransactionTests.java b/jooq/src/test/java/com/ankurm/jooq/TransactionTests.java new file mode 100644 index 0000000..4ce094f --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/TransactionTests.java @@ -0,0 +1,57 @@ +package com.ankurm.jooq; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.IOException; + +import static com.ankurm.jooq.generated.Tables.*; +import static org.junit.jupiter.api.Assertions.*; + +class TransactionTests extends PostgresTestBase { + + @Autowired StockService service; + + private int authors() { return dsl.fetchCount(AUTHOR); } + private boolean authorExists(String name) { return dsl.fetchExists(AUTHOR, AUTHOR.NAME.eq(name)); } + + @Test + void transactionBehaviour() { + Transcript t = new Transcript("08-transactions.txt"); + t.line("seeded authors: %d", authors()); + + assertThrows(IllegalStateException.class, service::noTransactionThenFail); + t.line("1. no @Transactional, exception after 2 inserts -> author persisted: %s, book persisted: %s", + authorExists("No Tx Author"), dsl.fetchExists(BOOK, BOOK.ISBN.eq("NT-1"))); + assertTrue(authorExists("No Tx Author")); + + assertThrows(IllegalStateException.class, service::springTransactionRuntimeFailure); + t.line("2. @Transactional, RuntimeException -> author persisted: %s, book persisted: %s", + authorExists("Rolled Back Author"), dsl.fetchExists(BOOK, BOOK.ISBN.eq("RB-1"))); + assertFalse(authorExists("Rolled Back Author")); + + assertThrows(IOException.class, service::springTransactionCheckedFailure); + t.line("3. @Transactional, checked IOException -> author persisted: %s, book persisted: %s", + authorExists("Checked Author"), dsl.fetchExists(BOOK, BOOK.ISBN.eq("CK-1"))); + assertTrue(authorExists("Checked Author")); + + assertThrows(IOException.class, service::springTransactionCheckedFailureWithRollbackFor); + t.line("4. @Transactional(rollbackFor=Exception.class) -> author persisted: %s, book persisted: %s", + authorExists("Checked Author 2"), dsl.fetchExists(BOOK, BOOK.ISBN.eq("CK-2"))); + assertFalse(authorExists("Checked Author 2")); + + String msg = service.nestedTransactionSavepoint(); + t.line("5. dsl.transaction inside @Transactional, inner fails, caught -> %s", msg); + t.line(" outer author persisted: %s, inner author persisted: %s", authorExists("Outer Author"), authorExists("Inner Author")); + assertTrue(authorExists("Outer Author")); + assertFalse(authorExists("Inner Author")); + + service.jooqTransactionOnly("jOOQ Tx OK", false); + assertThrows(IllegalStateException.class, () -> service.jooqTransactionOnly("jOOQ Tx Failed", true)); + t.line("6. dsl.transaction alone: success persisted: %s; failure persisted: %s", + authorExists("jOOQ Tx OK"), authorExists("jOOQ Tx Failed")); + assertTrue(authorExists("jOOQ Tx OK")); + assertFalse(authorExists("jOOQ Tx Failed")); + t.write(); + } +} diff --git a/jooq/src/test/java/com/ankurm/jooq/Transcript.java b/jooq/src/test/java/com/ankurm/jooq/Transcript.java new file mode 100644 index 0000000..7aa0a3a --- /dev/null +++ b/jooq/src/test/java/com/ankurm/jooq/Transcript.java @@ -0,0 +1,29 @@ +package com.ankurm.jooq; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Writes output/NN-*.txt while a test asserts the same numbers. */ +final class Transcript { + private final List lines = new ArrayList<>(); + private final Path file; + + Transcript(String name) { this.file = Path.of("output/" + name); } + + Transcript line(String fmt, Object... args) { + String s = fmt.formatted(args); + lines.add(s); + System.out.println(s); + return this; + } + + void write() { + try { + Files.createDirectories(file.getParent()); + Files.writeString(file, String.join("\n", lines) + "\n"); + } catch (IOException e) { throw new RuntimeException(e); } + } +}