Repository navigation
Expand file tree
/
Copy pathPostgresIntegrationTest.java
More file actions
2105 lines (1763 loc) · 69.3 KB
/
Copy pathPostgresIntegrationTest.java
File metadata and controls
2105 lines (1763 loc) · 69.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dev.sqlcj.compiler;
import dev.sqlcj.config.Config;
import dev.sqlcj.config.JavaConfig;
import dev.sqlcj.config.SqlConfig;
import dev.sqlcj.runtime.JdbcQueryExecutor;
import dev.sqlcj.runtime.QueryCardinalityException;
import dev.sqlcj.runtime.QueryExecutor;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.junit.jupiter.api.io.TempDir;
import org.postgresql.ds.PGSimpleDataSource;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;
import javax.sql.DataSource;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.RecordComponent;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Executes the compiler pipeline end to end against a real PostgreSQL
* instance: the accepted schema snapshot is run as PostgreSQL DDL, the
* generated Java is compiled, and the generated classes are executed through
* the JDBC runtime.
*
* <p>The whole class is skipped when Docker is unavailable, so that
* {@code mvn test} stays runnable without Docker. Setting
* {@code -Dsqlcj.test.requireDocker=true}, as continuous integration does,
* turns an unavailable Docker into a failure instead of a skip.
*/
@EnabledIf("dockerAvailable")
class PostgresIntegrationTest {
/**
* System property that forbids skipping these tests. Continuous
* integration sets it so that a broken Docker environment fails the build
* instead of silently reducing coverage.
*/
private static final String REQUIRE_DOCKER_PROPERTY = "sqlcj.test.requireDocker";
/** The configured query-group name, which generates {@code UsersRepository}. */
private static final String GROUP = "Users";
private static final String SCHEMA = """
CREATE TABLE users
(
id BIGINT PRIMARY KEY,
code INTEGER NOT NULL,
score SMALLINT,
name VARCHAR(255),
bio TEXT,
active BOOLEAN,
birth_date DATE,
created_at TIMESTAMP,
balance DECIMAL(10, 2),
serial_id SERIAL,
revision BIGSERIAL,
external_id UUID,
updated_at TIMESTAMP(3) WITH TIME ZONE
);
""";
/**
* A snapshot whose table-level foreign key and check constraints are
* accepted and ignored by the schema parser, together with the column
* defaults and named constraints that surround them.
*/
private static final String CONSTRAINT_SCHEMA = """
CREATE TABLE customers
(
id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
CONSTRAINT customers_pk PRIMARY KEY (id),
CONSTRAINT customers_name_unique UNIQUE (name)
);
CREATE TABLE customer_orders
(
id BIGINT NOT NULL,
customer_id BIGINT NOT NULL,
quantity INTEGER NOT NULL DEFAULT 1,
status VARCHAR(32) DEFAULT 'new',
created_at TIMESTAMP DEFAULT now(),
PRIMARY KEY (id),
CONSTRAINT customer_orders_customer_fk FOREIGN KEY (customer_id)
REFERENCES customers (id) ON DELETE CASCADE,
CONSTRAINT customer_orders_quantity_check CHECK (quantity > 0),
CHECK (status <> '')
);
""";
/**
* A snapshot that declares every supported type through its PostgreSQL
* spelling, including the serial spellings, which PostgreSQL fills from
* their own sequences.
*/
private static final String ALIAS_SCHEMA = """
CREATE TABLE user_aliases
(
id INT8 PRIMARY KEY,
code INT4 NOT NULL,
score INT2,
label CHARACTER VARYING(20),
tag CHAR(3),
initials CHARACTER(3),
created_at TIMESTAMP(3) WITHOUT TIME ZONE,
updated_at TIMESTAMPTZ,
small_serial SMALLSERIAL,
serial_two SERIAL2,
serial_four SERIAL4,
serial_eight SERIAL8
);
""";
/**
* A snapshot that declares every accepted floating-point, binary, and time
* spelling, each of them nullable so that one row can carry values and
* another can carry nulls.
*/
private static final String MEASUREMENT_SCHEMA = """
CREATE TABLE measurements
(
id BIGINT PRIMARY KEY,
amount REAL,
ratio FLOAT4,
total DOUBLE PRECISION,
average FLOAT8,
payload BYTEA,
opened_at TIME,
closed_at TIME(3) WITHOUT TIME ZONE
);
""";
/**
* A snapshot declaring one nullable column of each JSON spelling, so that
* one row can carry JSON text and another can carry nulls.
*/
private static final String DOCUMENT_SCHEMA = """
CREATE TABLE documents
(
id BIGINT PRIMARY KEY,
payload JSON,
config JSONB
);
""";
/**
* Queries used by the caller-owned transaction tests: an affected-row
* write, a returning write, and a read.
*/
private static final String TRANSACTION_QUERIES = """
-- name: InsertUser :exec
INSERT INTO users (id, code, name)
VALUES ($1, $2, $3);
-- name: InsertUserReturningRow :one
INSERT INTO users (id, code, name)
VALUES ($1, $2, $3)
RETURNING id, name;
-- name: ListUserNames :many
SELECT name
FROM users
ORDER BY id;
""";
/**
* Queries used by the cardinality test: the same predicate on the
* non-unique {@code code} column declared with each result annotation.
*/
private static final String CARDINALITY_QUERIES = """
-- name: GetUserByCode :one
SELECT id, name
FROM users
WHERE code = $1;
-- name: FindUserByCode :optional
SELECT id, name
FROM users
WHERE code = $1;
-- name: ListUsersByCode :many
SELECT id, name
FROM users
WHERE code = $1
ORDER BY id;
""";
/** The first migration file of the migration-directory fixture. */
private static final String REGION_MIGRATION = """
CREATE TABLE region (
code text PRIMARY KEY,
title text NOT NULL
);
""";
/**
* The second migration file, without the {@code COMMENT ON TYPE} statement
* JSqlParser does not parse, so that the directory loads.
*/
private static final String STAGE_MIGRATION = """
CREATE TYPE stage_setting AS ENUM ('indoor', 'outdoor');
CREATE TABLE stages (
id SERIAL PRIMARY KEY,
handle text NOT NULL,
legacy_code text,
setting stage_setting NOT NULL,
past_settings stage_setting[],
title varchar(120) NOT NULL,
region text NOT NULL REFERENCES region (code),
keywords text[]
);
COMMENT ON TABLE stages IS 'Places where performances happen';
COMMENT ON COLUMN stages.handle IS 'Appears in public links';
""";
/** The third migration file, which reshapes the table the second creates. */
private static final String RESHAPE_STAGE_MIGRATION = """
ALTER TABLE stages RENAME TO stage;
ALTER TABLE stage DROP COLUMN legacy_code;
ALTER TABLE stage ADD COLUMN opened_at TIMESTAMP NOT NULL DEFAULT now();
""";
/** Queries over the tables the migration directory leaves. */
private static final String MIGRATED_QUERIES = """
-- name: CreateRegion :one
INSERT INTO region (code, title) VALUES ($1, $2) RETURNING *;
-- name: GetStage :one
SELECT id, handle, title, region, opened_at FROM stage WHERE handle = $1 AND region = $2;
""";
private static final UUID EXTERNAL_ID = UUID.fromString("3f2504e0-4f89-11d3-9a0c-0305e82c3301");
private static final OffsetDateTime UPDATED_AT = OffsetDateTime.of(
2026,
1,
1,
10,
0,
0,
0,
ZoneOffset.ofHours(3)
);
private static PostgreSQLContainer<?> postgres;
private static DataSource dataSource;
@TempDir
Path tempDir;
static boolean dockerAvailable() {
boolean available = DockerClientFactory.instance().isDockerAvailable();
if (!available && Boolean.getBoolean(REQUIRE_DOCKER_PROPERTY)) {
throw new IllegalStateException(
"Docker is unavailable, but " + REQUIRE_DOCKER_PROPERTY + " requires these tests to run."
);
}
return available;
}
@BeforeAll
static void startPostgres() {
postgres = new PostgreSQLContainer<>(
DockerImageName.parse("postgres:16-alpine")
);
postgres.start();
PGSimpleDataSource postgresDataSource = new PGSimpleDataSource();
postgresDataSource.setUrl(postgres.getJdbcUrl());
postgresDataSource.setUser(postgres.getUsername());
postgresDataSource.setPassword(postgres.getPassword());
dataSource = postgresDataSource;
}
@AfterAll
static void stopPostgres() {
if (postgres != null) {
postgres.stop();
}
}
/**
* Recreates the database state from the same schema snapshot text the
* compiler accepts, so the snapshot is proven to be valid PostgreSQL DDL.
*/
@BeforeEach
void resetDatabase() throws Exception {
execute("DROP TABLE IF EXISTS stage");
execute("DROP TABLE IF EXISTS region");
execute("DROP TYPE IF EXISTS stage_setting");
execute("DROP TABLE IF EXISTS customer_orders");
execute("DROP TABLE IF EXISTS customers");
execute("DROP TABLE IF EXISTS measurements");
execute("DROP TABLE IF EXISTS documents");
execute("DROP TABLE IF EXISTS user_aliases");
execute("DROP TABLE IF EXISTS users");
execute(SCHEMA);
}
@Test
void shouldExecuteGeneratedOneQueryAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: GetUser :one
SELECT id, code, score, name, bio, active, birth_date, created_at, balance
FROM users
WHERE id = $1
AND active = $2;
""");
execute("""
INSERT INTO users
(id, code, score, name, bio, active, birth_date, created_at, balance)
VALUES
(1, 42, 7, 'Alice', 'first user', TRUE, DATE '1990-01-15',
TIMESTAMP '2026-01-01 10:00:00', 100.50)
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method method = repository.getClass().getMethod(
"getUser",
Long.class,
Boolean.class
);
Object result = method.invoke(repository, 1L, Boolean.TRUE);
assertNotNull(result);
assertEquals(
List.of(
"id",
"code",
"score",
"name",
"bio",
"active",
"birthDate",
"createdAt",
"balance"
),
recordComponentNames(result)
);
assertEquals(1L, component(result, "id"));
assertEquals(42, component(result, "code"));
assertEquals((short) 7, component(result, "score"));
assertEquals("Alice", component(result, "name"));
assertEquals("first user", component(result, "bio"));
assertEquals(true, component(result, "active"));
assertEquals(LocalDate.of(1990, 1, 15), component(result, "birthDate"));
assertEquals(
LocalDateTime.of(2026, 1, 1, 10, 0),
component(result, "createdAt")
);
assertEquals(
new BigDecimal("100.50"),
component(result, "balance")
);
}
}
@Test
void shouldExecuteGeneratedManyQueryAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: ListUsers :many
SELECT id, name
FROM users
WHERE active = $1
ORDER BY id;
""");
execute("""
INSERT INTO users (id, code, name, active)
VALUES
(3, 3, 'Charlie', TRUE),
(1, 1, 'Alice', TRUE),
(2, 2, 'Bob', FALSE),
(4, 4, 'Dora', TRUE)
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method method = repository.getClass().getMethod(
"listUsers",
Boolean.class
);
Object result = method.invoke(repository, Boolean.TRUE);
assertInstanceOf(List.class, result);
List<?> users = (List<?>) result;
assertEquals(3, users.size());
assertEquals(List.of("id", "name"), recordComponentNames(users.getFirst()));
assertEquals(1L, component(users.get(0), "id"));
assertEquals("Alice", component(users.get(0), "name"));
assertEquals(3L, component(users.get(1), "id"));
assertEquals("Charlie", component(users.get(1), "name"));
assertEquals(4L, component(users.get(2), "id"));
assertEquals("Dora", component(users.get(2), "name"));
}
}
/**
* Covers the text and null predicates end to end: a {@code LIKE} pattern on
* a {@code VARCHAR} column, a case-insensitive {@code ILIKE} pattern on a
* {@code TEXT} column, and both null tests are generated, compiled, and
* executed against PostgreSQL.
*/
@Test
void shouldExecuteGeneratedTextAndNullPredicatesAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: SearchUsersByName :many
SELECT id, name
FROM users
WHERE name LIKE $1
ORDER BY id;
-- name: SearchUsersByBio :many
SELECT id, name
FROM users
WHERE bio LIKE $1
ORDER BY id;
-- name: SearchUsersByBioIgnoringCase :many
SELECT u.id, u.name
FROM users u
WHERE u.bio ILIKE $1
ORDER BY u.id;
-- name: ListUsersWithoutBio :many
SELECT id, name
FROM users
WHERE bio IS NULL
ORDER BY id;
-- name: ListUsersWithBio :many
SELECT id, name
FROM users u
WHERE u.bio IS NOT NULL
ORDER BY id;
""");
execute("""
INSERT INTO users (id, code, name, bio)
VALUES
(1, 1, 'Alice', 'Writes POETRY'),
(2, 2, 'Albert', NULL),
(3, 3, 'Bob', 'writes poetry too')
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method searchByName = repository.getClass().getMethod(
"searchUsersByName",
String.class
);
Method searchByBio = repository.getClass().getMethod(
"searchUsersByBio",
String.class
);
Method searchByBioIgnoringCase = repository.getClass().getMethod(
"searchUsersByBioIgnoringCase",
String.class
);
assertEquals(
List.of("Alice", "Albert"),
names(searchByName.invoke(repository, "Al%"))
);
assertEquals(
List.of("Alice"),
names(searchByBio.invoke(repository, "%POETRY%"))
);
assertEquals(
List.of("Alice", "Bob"),
names(searchByBioIgnoringCase.invoke(repository, "%POETRY%"))
);
assertEquals(
List.of("Albert"),
names(
repository
.getClass()
.getMethod("listUsersWithoutBio")
.invoke(repository)
)
);
assertEquals(
List.of("Alice", "Bob"),
names(
repository
.getClass()
.getMethod("listUsersWithBio")
.invoke(repository)
)
);
}
}
/**
* Covers the range predicates end to end: a {@code BETWEEN} range and a
* {@code NOT BETWEEN} range whose bounds use out-of-order placeholder
* indexes are generated, compiled, and executed against PostgreSQL, so a
* swapped binding order would change the returned names.
*/
@Test
void shouldExecuteGeneratedRangePredicatesAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: ListUsersInCodeRange :many
SELECT id, name
FROM users
WHERE code BETWEEN $1 AND $2
ORDER BY id;
-- name: ListUsersOutsideCodeRange :many
SELECT id, name
FROM users
WHERE code NOT BETWEEN $2 AND $1
ORDER BY id;
""");
execute("""
INSERT INTO users (id, code, name)
VALUES
(1, 5, 'Alice'),
(2, 20, 'Bob'),
(3, 40, 'Cara')
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method inRange = repository.getClass().getMethod(
"listUsersInCodeRange",
Integer.class,
Integer.class
);
Method outsideRange = repository.getClass().getMethod(
"listUsersOutsideCodeRange",
Integer.class,
Integer.class
);
assertEquals(
List.of("Bob"),
names(inRange.invoke(repository, 10, 30))
);
assertEquals(
List.of("Alice", "Cara"),
names(outsideRange.invoke(repository, 30, 10))
);
}
}
/**
* Covers pagination end to end: a {@code LIMIT ... OFFSET ...} page and the
* same page written as {@code OFFSET ... LIMIT ...} are generated,
* compiled, and executed against PostgreSQL, so a swapped binding order
* would change the returned page.
*/
@Test
void shouldExecuteGeneratedPaginationAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: ListUserPage :many
SELECT id, name
FROM users
ORDER BY id
LIMIT $1 OFFSET $2;
-- name: ListUserPageWithLeadingOffset :many
SELECT id, name
FROM users
ORDER BY id
OFFSET $2 LIMIT $1;
""");
execute("""
INSERT INTO users (id, code, name)
VALUES
(1, 1, 'Alice'),
(2, 2, 'Bob'),
(3, 3, 'Cara'),
(4, 4, 'Dora')
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method page = repository.getClass().getMethod(
"listUserPage",
Integer.class,
Integer.class
);
Method pageWithLeadingOffset = repository.getClass().getMethod(
"listUserPageWithLeadingOffset",
Integer.class,
Integer.class
);
assertEquals(
List.of("Bob", "Cara"),
names(page.invoke(repository, 2, 1))
);
assertEquals(
List.of("Bob", "Cara"),
names(pageWithLeadingOffset.invoke(repository, 2, 1))
);
}
}
/**
* Covers the scalar count end to end: a {@code :one} count read is
* generated, compiled, and executed against PostgreSQL, so its result
* record exposes one {@code Long} component that counts the matching rows
* and is {@code 0} when none match.
*/
@Test
void shouldExecuteGeneratedScalarCountAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: CountUsersByName :one
SELECT COUNT(*) AS total
FROM users
WHERE name LIKE $1;
""");
execute("""
INSERT INTO users (id, code, name)
VALUES
(1, 1, 'Alice'),
(2, 2, 'Amy'),
(3, 3, 'Bob')
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method count = repository.getClass().getMethod(
"countUsersByName",
String.class
);
Object matching = count.invoke(repository, "A%");
assertEquals(List.of("total"), recordComponentNames(matching));
assertEquals(
Long.class,
matching.getClass().getRecordComponents()[0].getType()
);
assertEquals(2L, component(matching, "total"));
assertEquals(0L, component(count.invoke(repository, "Z%"), "total"));
}
}
@Test
void shouldExecuteGeneratedWriteAgainstPostgres() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: InsertUser :exec
INSERT INTO users (id, code, name, birth_date, created_at, balance)
VALUES ($1, $2, $3, $4, $5, $6);
-- name: GetUser :one
SELECT id, code, name, birth_date, created_at, balance
FROM users
WHERE id = $1;
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method insertMethod = repository.getClass().getMethod(
"insertUser",
Long.class,
Integer.class,
String.class,
LocalDate.class,
LocalDateTime.class,
BigDecimal.class
);
Object affectedRows = insertMethod.invoke(
repository,
5L,
42,
"Alice",
LocalDate.of(1990, 1, 15),
LocalDateTime.of(2026, 1, 1, 10, 0),
new BigDecimal("100.50")
);
assertEquals(1, affectedRows);
Method queryMethod = repository.getClass().getMethod("getUser", Long.class);
Object result = queryMethod.invoke(repository, 5L);
assertNotNull(result);
assertEquals(5L, component(result, "id"));
assertEquals(42, component(result, "code"));
assertEquals("Alice", component(result, "name"));
assertEquals(LocalDate.of(1990, 1, 15), component(result, "birthDate"));
assertEquals(
LocalDateTime.of(2026, 1, 1, 10, 0),
component(result, "createdAt")
);
assertEquals(new BigDecimal("100.50"), component(result, "balance"));
}
}
/**
* Covers null parameter binding and null result reading for every nullable
* column type of the schema snapshot: the row is written through the
* generated write method with null arguments and read back through the
* generated read method.
*/
@Test
void shouldBindAndReadNullValuesThroughGeneratedCode() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: InsertUser :exec
INSERT INTO users
(id, code, score, name, bio, active, birth_date, created_at, balance,
external_id, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
-- name: GetUser :one
SELECT id, code, score, name, bio, active, birth_date, created_at, balance,
external_id, updated_at
FROM users
WHERE id = $1;
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method insertMethod = repository.getClass().getMethod(
"insertUser",
Long.class,
Integer.class,
Short.class,
String.class,
String.class,
Boolean.class,
LocalDate.class,
LocalDateTime.class,
BigDecimal.class,
UUID.class,
OffsetDateTime.class
);
Object affectedRows = insertMethod.invoke(
repository,
6L,
42,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
assertEquals(1, affectedRows);
Method queryMethod = repository.getClass().getMethod("getUser", Long.class);
Object result = queryMethod.invoke(repository, 6L);
assertNotNull(result);
assertEquals(6L, component(result, "id"));
assertEquals(42, component(result, "code"));
assertNull(component(result, "score"));
assertNull(component(result, "name"));
assertNull(component(result, "bio"));
assertNull(component(result, "active"));
assertNull(component(result, "birthDate"));
assertNull(component(result, "createdAt"));
assertNull(component(result, "balance"));
assertNull(component(result, "externalId"));
assertNull(component(result, "updatedAt"));
}
}
/**
* Covers the PostgreSQL round trip of the serial, UUID, and
* timestamptz mappings: every value is written through the generated
* write method and read back through the generated read method.
*
* <p>PostgreSQL normalizes a {@code timestamptz} to the session time zone,
* so the read value is compared by instant rather than by offset.
*/
@Test
void shouldRoundTripSerialUuidAndTimestampWithTimeZoneValues() throws Exception {
Path classesDirectory = generateAndCompile("""
-- name: InsertUser :exec
INSERT INTO users (id, code, serial_id, revision, external_id, updated_at)
VALUES ($1, $2, $3, $4, $5, $6);
-- name: GetUser :one
SELECT id, serial_id, revision, external_id, updated_at
FROM users
WHERE id = $1;
""");
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method insertMethod = repository.getClass().getMethod(
"insertUser",
Long.class,
Integer.class,
Integer.class,
Long.class,
UUID.class,
OffsetDateTime.class
);
Object affectedRows = insertMethod.invoke(
repository,
7L,
42,
101,
202L,
EXTERNAL_ID,
UPDATED_AT
);
assertEquals(1, affectedRows);
Method queryMethod = repository.getClass().getMethod("getUser", Long.class);
Object result = queryMethod.invoke(repository, 7L);
assertNotNull(result);
assertEquals(
List.of("id", "serialId", "revision", "externalId", "updatedAt"),
recordComponentNames(result)
);
assertEquals(7L, component(result, "id"));
assertEquals(101, component(result, "serialId"));
assertEquals(202L, component(result, "revision"));
assertEquals(EXTERNAL_ID, component(result, "externalId"));
OffsetDateTime updatedAt = assertInstanceOf(
OffsetDateTime.class,
component(result, "updatedAt")
);
assertEquals(UPDATED_AT.toInstant(), updatedAt.toInstant());
}
}
/**
* Proves that a snapshot declaring the PostgreSQL type spellings is valid
* PostgreSQL DDL and round trips through generated code: the non-serial
* columns are written through the generated write method and read back with
* the Java types the spellings map to, while the omitted serial columns are
* filled by their sequences.
*
* <p>PostgreSQL blank-pads a {@code character} value to the declared
* length, so {@code "ab"} written into {@code CHAR(3)} reads back as
* {@code "ab "}. A {@code timestamptz} is normalized to the session time
* zone, so it is compared by instant.
*/
@Test
void shouldRoundTripPostgresTypeSpellingValues() throws Exception {
execute(ALIAS_SCHEMA);
Path classesDirectory = generateAndCompile(
ALIAS_SCHEMA,
"""
-- name: InsertUserAlias :exec
INSERT INTO user_aliases
(id, code, score, label, tag, initials, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
-- name: GetUserAlias :one
SELECT id, code, score, label, tag, initials, created_at, updated_at,
small_serial, serial_two, serial_four, serial_eight
FROM user_aliases
WHERE id = $1;
"""
);
try (URLClassLoader classLoader = classLoader(classesDirectory)) {
Object repository = newRepository(classLoader);
Method insertMethod = repository.getClass().getMethod(
"insertUserAlias",
Long.class,
Integer.class,
Short.class,
String.class,
String.class,
String.class,
LocalDateTime.class,
OffsetDateTime.class
);
Object affectedRows = insertMethod.invoke(
repository,
8L,
42,
(short) 7,
"gold",
"ab",
"xyz",
LocalDateTime.of(2026, 1, 1, 10, 0),
UPDATED_AT
);
assertEquals(1, affectedRows);
Object result = repository
.getClass()
.getMethod("getUserAlias", Long.class)
.invoke(repository, 8L);
assertNotNull(result);
assertEquals(
List.of(
"id",
"code",
"score",
"label",
"tag",
"initials",
"createdAt",
"updatedAt",