-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathJdbcMockServerTest.java
More file actions
5476 lines (5033 loc) · 242 KB
/
JdbcMockServerTest.java
File metadata and controls
5476 lines (5033 loc) · 242 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
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.cloud.spanner.pgadapter;
import static com.google.cloud.spanner.pgadapter.statements.BackendConnection.TRANSACTION_ABORTED_ERROR;
import static com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgNamespace.PG_NAMESPACE_CTE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.NoCredentials;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.MockSpannerServiceImpl;
import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime;
import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.connection.RandomResultSetGenerator;
import com.google.cloud.spanner.pgadapter.error.SQLState;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.EmptyPgEnum;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgAttrdef;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgAttribute;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgCollation;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgConstraint;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgExtension;
import com.google.cloud.spanner.pgadapter.statements.PgCatalog.PgIndex;
import com.google.cloud.spanner.pgadapter.utils.ClientAutoDetector.WellKnownClient;
import com.google.cloud.spanner.pgadapter.wireprotocol.ControlMessage.PreparedType;
import com.google.cloud.spanner.pgadapter.wireprotocol.DescribeMessage;
import com.google.cloud.spanner.pgadapter.wireprotocol.ExecuteMessage;
import com.google.cloud.spanner.pgadapter.wireprotocol.ParseMessage;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.ListValue;
import com.google.protobuf.Value;
import com.google.spanner.admin.database.v1.GetDatabaseDdlResponse;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest;
import com.google.spanner.v1.BeginTransactionRequest;
import com.google.spanner.v1.CommitRequest;
import com.google.spanner.v1.ExecuteBatchDmlRequest;
import com.google.spanner.v1.ExecuteSqlRequest;
import com.google.spanner.v1.ExecuteSqlRequest.QueryMode;
import com.google.spanner.v1.ResultSetMetadata;
import com.google.spanner.v1.ResultSetStats;
import com.google.spanner.v1.RollbackRequest;
import com.google.spanner.v1.StructType;
import com.google.spanner.v1.StructType.Field;
import com.google.spanner.v1.Type;
import com.google.spanner.v1.TypeAnnotationCode;
import com.google.spanner.v1.TypeCode;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Status;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Types;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.postgresql.PGConnection;
import org.postgresql.PGStatement;
import org.postgresql.core.Oid;
import org.postgresql.jdbc.PgStatement;
import org.postgresql.util.PGobject;
import org.postgresql.util.PSQLException;
@RunWith(Parameterized.class)
public class JdbcMockServerTest extends AbstractMockServerTest {
private static final int RANDOM_RESULTS_ROW_COUNT = 10;
private static final Statement SELECT_RANDOM = Statement.of("select * from random_table");
private static final ImmutableList<String> JDBC_STARTUP_STATEMENTS =
ImmutableList.of(
"SET extra_float_digits = 3", "SET application_name = 'PostgreSQL JDBC Driver'");
@Parameter public String pgVersion;
@Parameters(name = "pgVersion = {0}")
public static Object[] data() {
return new Object[] {"1.0", "14.1"};
}
@BeforeClass
public static void loadPgJdbcDriver() throws Exception {
// Make sure the PG JDBC driver is loaded.
Class.forName("org.postgresql.Driver");
addRandomResultResults();
setupJsonbResults();
}
private static void addRandomResultResults() {
RandomResultSetGenerator generator =
new RandomResultSetGenerator(RANDOM_RESULTS_ROW_COUNT, Dialect.POSTGRESQL);
mockSpanner.putStatementResult(StatementResult.query(SELECT_RANDOM, generator.generate()));
}
static void setupJsonbResults() {
setupJsonbResults(mockSpanner);
}
static void setupJsonbResults(MockSpannerServiceImpl mockSpanner) {
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT t.oid, t.typname "
+ "FROM pg_type t "
+ "JOIN pg_namespace n ON t.typnamespace = n.oid "
+ "WHERE t.typelem = (SELECT oid FROM pg_type WHERE typname = $1) AND substring(t.typname, 1, 1) = '_' AND t.typlen = -1 AND (n.nspname = $2 OR $3 AND n.nspname IN ('pg_catalog', 'public')) "
+ "ORDER BY t.typelem DESC LIMIT 1")
.bind("p1")
.to("jsonb")
.bind("p2")
.to((String) null)
.bind("p3")
.to(true)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(createMetadata(ImmutableList.of(TypeCode.INT64, TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("3807").build())
.addValues(Value.newBuilder().setStringValue("_jsonb").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT n.nspname IN ('pg_catalog', 'public'), n.nspname, t.typname "
+ "FROM pg_type t JOIN pg_namespace n ON t.typnamespace = n.oid "
+ "WHERE t.oid = $1")
.bind("p1")
.to(3802L)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.BOOL, TypeCode.STRING, TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStringValue("pg_catalog").build())
.addValues(Value.newBuilder().setStringValue("jsonb").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT n.nspname IN ('pg_catalog', 'public'), n.nspname, t.typname "
+ "FROM pg_type t JOIN pg_namespace n ON t.typnamespace = n.oid "
+ "WHERE t.oid = $1")
.bind("p1")
.to(3807L)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.BOOL, TypeCode.STRING, TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStringValue("pg_catalog").build())
.addValues(Value.newBuilder().setStringValue("_jsonb").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT e.typdelim FROM pg_type t, pg_type e WHERE t.oid = $1 and t.typelem = e.oid")
.bind("p1")
.to(3807L)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(createMetadata(ImmutableList.of(TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue(",").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT e.oid, n.nspname IN ('pg_catalog', 'public'), n.nspname, e.typname "
+ "FROM pg_type t JOIN pg_type e ON t.typelem = e.oid "
+ "JOIN pg_namespace n ON t.typnamespace = n.oid "
+ "WHERE t.oid = $1")
.bind("p1")
.to(3807L)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(
TypeCode.INT64, TypeCode.BOOL, TypeCode.STRING, TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("3802").build())
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStringValue("pg_catalog").build())
.addValues(Value.newBuilder().setStringValue("jsonb").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT t.typarray, arr.typname "
+ "FROM pg_type t "
+ "JOIN pg_namespace n ON t.typnamespace = n.oid "
+ "JOIN pg_type arr ON arr.oid = t.typarray "
+ "WHERE t.typname = $1 "
+ "AND (n.nspname = $2 OR $3 AND n.nspname IN ('pg_catalog', 'public')) "
+ "ORDER BY t.oid DESC LIMIT 1")
.bind("p1")
.to("jsonb")
.bind("p2")
.to((String) null)
.bind("p3")
.to(true)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(createMetadata(ImmutableList.of(TypeCode.INT64, TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("3807").build())
.addValues(Value.newBuilder().setStringValue("_jsonb").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT substring(typname, 1, 1)='_' as is_array, typtype, typname, pg_type.oid "
+ "FROM pg_type "
+ "LEFT JOIN (select ns.oid as nspoid, ns.nspname, r.r from pg_namespace as ns join ( select 1 as r, 'public' as nspname ) as r using ( nspname ) ) as sp ON sp.nspoid = typnamespace "
+ "WHERE pg_type.oid = $1 "
+ "ORDER BY sp.r, pg_type.oid DESC")
.bind("p1")
.to(3807L)
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
ResultSetMetadata.newBuilder()
.setRowType(
StructType.newBuilder()
.addFields(
Field.newBuilder()
.setName("is_array")
.setType(Type.newBuilder().setCode(TypeCode.BOOL).build())
.build())
.addFields(
Field.newBuilder()
.setName("typtype")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.addFields(
Field.newBuilder()
.setName("typename")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.addFields(
Field.newBuilder()
.setName("oid")
.setType(Type.newBuilder().setCode(TypeCode.INT64).build())
.build())
.build())
.build())
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStringValue("b").build())
.addValues(Value.newBuilder().setStringValue("_jsonb").build())
.addValues(Value.newBuilder().setStringValue("3807").build())
.build())
.build()));
mockSpanner.putStatementResult(
StatementResult.query(
Statement.newBuilder(
"with "
+ PG_TYPE_PREFIX
+ "\nSELECT typinput='pg_catalog.array_in'::regproc as is_array, typtype, typname, pg_type.oid "
+ "FROM pg_type "
+ "LEFT JOIN (select ns.oid as nspoid, ns.nspname, r.r from pg_namespace as ns join ( select s.r, (current_schemas(false))[s.r] as nspname from generate_series(1, array_upper(current_schemas(false), 1)) as s(r) ) as r using ( nspname ) ) as sp ON sp.nspoid = typnamespace "
+ "WHERE pg_type.oid = $1 "
+ "ORDER BY sp.r, pg_type.oid DESC")
.build(),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
ResultSetMetadata.newBuilder()
.setRowType(
StructType.newBuilder()
.addFields(
Field.newBuilder()
.setName("is_array")
.setType(Type.newBuilder().setCode(TypeCode.BOOL).build())
.build())
.addFields(
Field.newBuilder()
.setName("typtype")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.addFields(
Field.newBuilder()
.setName("typename")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.addFields(
Field.newBuilder()
.setName("oid")
.setType(Type.newBuilder().setCode(TypeCode.INT64).build())
.build())
.build())
.build())
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStringValue("b").build())
.addValues(Value.newBuilder().setStringValue("_jsonb").build())
.addValues(Value.newBuilder().setStringValue("3807").build())
.build())
.build()));
}
/**
* Creates a JDBC connection string that instructs the PG JDBC driver to use the default extended
* mode for queries and DML statements.
*/
private String createUrl() {
return String.format(
"jdbc:postgresql://localhost:%d/?options=-c%%20server_version=%s",
pgServer.getLocalPort(), pgVersion);
}
private String getExpectedInitialApplicationName() {
return pgVersion.equals("1.0") ? "jdbc" : "PostgreSQL JDBC Driver";
}
@Test
public void testQuery() throws SQLException {
String sql = "SELECT 1";
try (Connection connection = DriverManager.getConnection(createUrl())) {
try (ResultSet resultSet = connection.createStatement().executeQuery(sql)) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertFalse(resultSet.next());
}
}
// The statement is only sent once to the mock server. The DescribePortal message will trigger
// the execution of the query, and the result from that execution will be used for the Execute
// message.
assertEquals(1, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class));
ExecuteSqlRequest executeRequest =
mockSpanner.getRequestsOfType(ExecuteSqlRequest.class).get(0);
assertEquals(QueryMode.NORMAL, executeRequest.getQueryMode());
for (ExecuteSqlRequest request : mockSpanner.getRequestsOfType(ExecuteSqlRequest.class)) {
assertEquals(sql, request.getSql());
assertTrue(request.getTransaction().hasSingleUse());
assertTrue(request.getTransaction().getSingleUse().hasReadOnly());
}
// Verify that a header was sent to Spanner to indicate which client was connected to PGAdapter.
assertTrue(
WELL_KNOWN_CLIENT_HEADERS.toString(),
WELL_KNOWN_CLIENT_HEADERS.contains(WellKnownClient.JDBC.name()));
}
@Test
public void testSelectHelloWorld() throws SQLException {
String randomString =
"╍➗⡢ⵄ⯣⺫␐Ⓔ⠊⓭∲Ⳋ⤄▹⡨⿄⦺⒢⠱\u2E5E⾀⭯⛧⫶⏵⽐⓮⻋⥍\u242A⫌⏎⎽⚚⒊ↄ⦛⹐⌣⸤ⳅ⼑╪␦⻛➯⃝⡥⨬⸺⇊⹐┪⍦╳◄⪷ⴺ⽾⣌⛛⬗⍘⧤⃰⩧⬔⇌⣸⮽❨⫘ⱶ⣗⤶⢽⚶⒪⁙♤✾✟⏩⟞\u20C5℈⺙ⵠ⋛✧⧬⯨➛⌁⻚ⰷ∑⼫⊅ⷛ";
String sql = String.format("SELECT '%s'", randomString);
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(createMetadata(ImmutableList.of(TypeCode.STRING)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue(randomString).build())
.build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl())) {
for (int bufferSize : new int[] {0, 32}) {
connection
.createStatement()
.execute(String.format("set spanner.string_conversion_buffer_size=%d", bufferSize));
try (ResultSet resultSet = connection.createStatement().executeQuery(sql)) {
assertTrue(resultSet.next());
assertEquals(randomString, resultSet.getString(1));
assertFalse(resultSet.next());
}
}
}
}
@Test
public void testJsonbBinary() throws SQLException {
String randomString =
"{\"key\": \"╍➗⡢ⵄ⯣⺫␐Ⓔ⠊⓭∲Ⳋ⤄▹⡨⿄⦺⒢⠱\u2E5E⾀⭯⛧⫶⏵⽐⓮⻋⥍\u242A⫌⏎⎽⚚⒊ↄ⦛⹐⌣⸤ⳅ⼑╪␦⻛➯⃝⡥⨬⸺⇊⹐┪⍦╳◄⪷ⴺ⽾⣌⛛⬗⍘⧤⃰⩧⬔⇌⣸⮽❨⫘ⱶ⣗⤶⢽⚶⒪⁙♤✾✟⏩⟞\u20C5℈⺙ⵠ⋛✧⧬⯨➛⌁⻚ⰷ∑⼫⊅ⷛ\"}";
String sql = String.format("SELECT '%s'::jsonb", randomString);
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(createMetadata(ImmutableList.of(TypeCode.JSON)))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue(randomString).build())
.build())
.build()));
String binaryTransfer = "&binaryTransferEnable=" + Oid.JSONB;
try (Connection connection = DriverManager.getConnection(createUrl() + binaryTransfer)) {
connection.unwrap(PGConnection.class).setPrepareThreshold(-1);
for (int bufferSize : new int[] {0, 32}) {
connection
.createStatement()
.execute(String.format("set spanner.string_conversion_buffer_size=%d", bufferSize));
try (ResultSet resultSet = connection.createStatement().executeQuery(sql)) {
assertTrue(resultSet.next());
assertNotNull(resultSet.getObject(1));
assertFalse(resultSet.next());
}
}
}
}
@Test
public void testGetCatalogs() throws SQLException {
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(
"with pg_database as (\n"
+ " select 0::bigint as oid,\n"
+ " catalog_name as datname,\n"
+ " 0::bigint as datdba,\n"
+ " 6::bigint as encoding,\n"
+ " 'c' as datlocprovider,\n"
+ " 'C' as datcollate,\n"
+ " 'C' as datctype,\n"
+ " false as datistemplate,\n"
+ " true as datallowconn,\n"
+ " -1::bigint as datconnlimit,\n"
+ " 0::bigint as datlastsysoid,\n"
+ " 0::bigint as datfrozenxid,\n"
+ " 0::bigint as datminmxid,\n"
+ " 0::bigint as dattablespace,\n"
+ " null as daticulocale,\n"
+ " null as daticurules,\n"
+ " null as datcollversion,\n"
+ " null as datacl from information_schema.information_schema_catalog_name\n"
+ ")\n"
+ "SELECT datname AS TABLE_CAT FROM pg_database WHERE datallowconn = true ORDER BY datname"),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
ResultSetMetadata.newBuilder()
.setRowType(
StructType.newBuilder()
.addFields(
Field.newBuilder()
.setName("TABLE_CAT")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.build())
.build())
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("test-database").build())
.build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl())) {
try (ResultSet catalogs = connection.getMetaData().getCatalogs()) {
assertTrue(catalogs.next());
assertEquals("test-database", catalogs.getString("TABLE_CAT"));
assertFalse(catalogs.next());
}
}
}
@Test
public void testStatementReturnGeneratedKeys() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql + "\nRETURNING *"),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
java.sql.Statement statement = connection.createStatement()) {
assertFalse(statement.execute(sql, java.sql.Statement.RETURN_GENERATED_KEYS));
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testStatementGetGeneratedKeys() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
mockSpanner.putStatementResult(StatementResult.update(Statement.of(sql), 1L));
try (Connection connection = DriverManager.getConnection(createUrl());
java.sql.Statement statement = connection.createStatement()) {
assertFalse(statement.execute(sql));
assertEquals(1, statement.getUpdateCount());
// This should return an empty result set.
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertFalse(resultSet.next());
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testStatementReturnGeneratedKeysForSelect() throws SQLException {
String sql = "select * from test";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
java.sql.Statement statement = connection.createStatement()) {
assertTrue(statement.execute(sql, java.sql.Statement.RETURN_GENERATED_KEYS));
assertEquals(-1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertFalse(resultSet.next());
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testStatementReturnColumnIndexes() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
try (Connection connection = DriverManager.getConnection(createUrl());
java.sql.Statement statement = connection.createStatement()) {
PSQLException exception =
assertThrows(PSQLException.class, () -> statement.execute(sql, new int[] {1}));
assertEquals(
"Returning autogenerated keys by column index is not supported.", exception.getMessage());
}
}
@Test
public void testStatementReturnColumnNames() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql + "\nRETURNING \"id\", \"value\""),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
java.sql.Statement statement = connection.createStatement()) {
assertFalse(statement.execute(sql, new String[] {"id", "value"}));
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testPreparedStatementReturnGeneratedKeys() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql + "\nRETURNING *"),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
assertFalse(statement.execute());
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testPreparedStatementReturnColumnIndexes() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
try (Connection connection = DriverManager.getConnection(createUrl())) {
PSQLException exception =
assertThrows(PSQLException.class, () -> connection.prepareStatement(sql, new int[] {1}));
// Yes, this error message is a bit inconsistent.
assertEquals("Returning autogenerated keys is not supported.", exception.getMessage());
}
}
@Test
public void testPreparedStatementReturnColumnNames() throws SQLException {
String sql = "insert into test (id, value) values (1, 'One')";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql + "\nRETURNING \"id\", \"value\""),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, new String[] {"id", "value"})) {
assertFalse(statement.execute(sql, new String[] {"id", "value"}));
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, new String[] {"id", "value"})) {
assertEquals(1, statement.executeUpdate(sql, new String[] {"id", "value"}));
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
}
}
@Test
public void testPreparedStatementReturnColumnNamesForDmlWithReturningClause()
throws SQLException {
// A DML statement that already contains a returning clause is not modified by the PG JDBC
// driver.
String sql = "insert into test (id, value) values (1, 'One') returning *";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, new String[] {"id", "value"})) {
assertFalse(statement.execute(sql, new String[] {"id", "value"}));
// The result is returned as an update count, although the statement did include a returning
// clause. This happens because the statement requested generated keys to be returned.
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, new String[] {"id", "value"})) {
assertEquals(1, statement.executeUpdate(sql, new String[] {"id", "value"}));
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
}
}
@Test
public void testReturnGeneratedKeysForUpdate() throws SQLException {
String sql = "update test set value='Two' where id=1";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql + "\nRETURNING *"),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("Two").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
assertFalse(statement.execute());
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("Two", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testReturnGeneratedKeysForDelete() throws SQLException {
String sql = "delete from test where id=1";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(sql + "\nRETURNING *"),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
createMetadata(
ImmutableList.of(TypeCode.INT64, TypeCode.STRING),
ImmutableList.of("id", "value")))
.addRows(
ListValue.newBuilder()
.addValues(Value.newBuilder().setStringValue("1").build())
.addValues(Value.newBuilder().setStringValue("One").build())
.build())
.setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl());
PreparedStatement statement =
connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
assertFalse(statement.execute());
assertEquals(1, statement.getUpdateCount());
try (ResultSet resultSet = statement.getGeneratedKeys()) {
assertTrue(resultSet.next());
assertEquals(1L, resultSet.getLong(1));
assertEquals("One", resultSet.getString(2));
}
assertFalse(statement.getMoreResults());
}
}
@Test
public void testShowApplicationName() throws SQLException {
try (Connection connection = DriverManager.getConnection(createUrl())) {
try (ResultSet resultSet =
connection.createStatement().executeQuery("show application_name")) {
assertTrue(resultSet.next());
// If the PG version is 1.0, the JDBC driver thinks that the server does not support the
// application_name property and does not send any value. That means that PGAdapter fills it
// in automatically based on the client that is detected.
// Otherwise, the JDBC driver includes its own name, and that is not overwritten by
// PGAdapter.
assertEquals(getExpectedInitialApplicationName(), resultSet.getString(1));
assertFalse(resultSet.next());
}
}
}
@Test
public void testShowWellKnownClient() throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format("jdbc:postgresql://localhost:%d/", pgServer.getLocalPort()))) {
try (ResultSet resultSet =
connection.createStatement().executeQuery("show spanner.well_known_client")) {
assertTrue(resultSet.next());
assertEquals("JDBC", resultSet.getString(1));
assertFalse(resultSet.next());
}
}
}
@Test
public void testSetWellKnownClient() throws SQLException {
for (String client : new String[] {"pgx", "npgsql", "sqlalchemy2"}) {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:postgresql://localhost:%d/?options=-c%%20spanner.well_known_client=%s",
pgServer.getLocalPort(), client))) {
try (ResultSet resultSet =
connection.createStatement().executeQuery("show spanner.well_known_client")) {
assertTrue(resultSet.next());
assertEquals(client.toUpperCase(), resultSet.getString(1));
assertFalse(resultSet.next());
}
PSQLException exception =
assertThrows(
PSQLException.class,
() -> connection.createStatement().execute("set spanner.well_known_client='foo'"));
assertNotNull(exception.getServerErrorMessage());
assertEquals(
"parameter \"spanner.well_known_client\" cannot be set after connection start",
exception.getServerErrorMessage().getMessage());
}
}
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:postgresql://localhost:%d/?options=-c%%20spanner.well_known_client=%s",
pgServer.getLocalPort(), "foo"))) {
try (ResultSet resultSet =
connection.createStatement().executeQuery("show spanner.well_known_client")) {
assertTrue(resultSet.next());
assertEquals("foo", resultSet.getString(1));
assertFalse(resultSet.next());
}
}
}
@Test
public void testPreparedStatementParameterMetadata() throws SQLException {
String sql = "SELECT * FROM foo WHERE id=? or value=?";
String pgSql = "SELECT * FROM foo WHERE id=$1 or value=$2";
mockSpanner.putStatementResult(
StatementResult.query(
Statement.of(pgSql),
com.google.spanner.v1.ResultSet.newBuilder()
.setMetadata(
ResultSetMetadata.newBuilder()
.setRowType(
StructType.newBuilder()
.addFields(
Field.newBuilder()
.setName("col1")
.setType(Type.newBuilder().setCode(TypeCode.INT64).build())
.build())
.addFields(
Field.newBuilder()
.setName("col2")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.build())
.setUndeclaredParameters(
StructType.newBuilder()
.addFields(
Field.newBuilder()
.setName("p1")
.setType(Type.newBuilder().setCode(TypeCode.INT64).build())
.build())
.addFields(
Field.newBuilder()
.setName("p2")
.setType(Type.newBuilder().setCode(TypeCode.STRING).build())
.build())
.build())
.build())
.build()));
try (Connection connection = DriverManager.getConnection(createUrl())) {
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
ParameterMetaData parameters = preparedStatement.getParameterMetaData();
assertEquals(2, parameters.getParameterCount());
assertEquals(Types.BIGINT, parameters.getParameterType(1));
assertEquals(Types.VARCHAR, parameters.getParameterType(2));
}
}
}
@Test
public void testInvalidQuery() throws SQLException {
String sql = "/ not a valid comment / SELECT 1";
try (Connection connection = DriverManager.getConnection(createUrl())) {
PSQLException exception =
assertThrows(PSQLException.class, () -> connection.createStatement().executeQuery(sql));
assertEquals(
"ERROR: Unknown statement: / not a valid comment / SELECT 1", exception.getMessage());
}
// The statement is not sent to the mock server.