-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathITJdbcPreparedStatementTest.java
1498 lines (1403 loc) · 63.7 KB
/
ITJdbcPreparedStatementTest.java
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 2019 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.jdbc.it;
import static com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator;
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.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import com.google.cloud.ByteArray;
import com.google.cloud.spanner.Database;
import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.jdbc.JsonType;
import com.google.cloud.spanner.testing.EmulatorSpannerHelper;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;
import java.util.TimeZone;
import java.util.UUID;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
/** Integration tests for JDBC {@link PreparedStatement}s. */
@Category(ParallelIntegrationTest.class)
@RunWith(Parameterized.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ITJdbcPreparedStatementTest extends ITAbstractJdbcTest {
@ClassRule public static JdbcIntegrationTestEnv env = new JdbcIntegrationTestEnv();
@Parameters(name = "Dialect = {0}")
public static List<DialectTestParameter> data() {
List<DialectTestParameter> params = new ArrayList<>();
params.add(new DialectTestParameter(Dialect.GOOGLE_STANDARD_SQL));
params.add(new DialectTestParameter(Dialect.POSTGRESQL));
return params;
}
@Parameter public DialectTestParameter dialect;
private Database database;
@Before
public void setup() {
assumeFalse(
"Emulator does not support PostgreSQL",
dialect.dialect == Dialect.POSTGRESQL && EmulatorSpannerHelper.isUsingEmulator());
database = env.getOrCreateDatabase(getDialect(), getMusicTablesDdl(getDialect()));
}
@Override
public Dialect getDialect() {
return dialect.dialect;
}
private static final class Singer {
private final long singerId;
private final String firstName;
private final String lastName;
private final byte[] singerInfo;
private final Date birthDate;
private static Singer of(String values) {
String[] array = values.split(",");
if (array.length != 5) {
throw new IllegalArgumentException(values);
}
return new Singer(
Long.parseLong(array[0]), // singer id
array[1].substring(1, array[1].length() - 1), // first name
array[2].substring(1, array[2].length() - 1), // last name
parseBytes(array[3].substring(13, array[3].length() - 2)), // singer info
parseDate(array[4].substring(6, array[4].length() - 1)) // birth date
);
}
private Singer(
long singerId, String firstName, String lastName, byte[] singerInfo, Date birthDate) {
this.singerId = singerId;
this.firstName = firstName;
this.lastName = lastName;
this.singerInfo = singerInfo;
this.birthDate = birthDate;
}
private void setPreparedStatement(PreparedStatement ps, Dialect dialect) throws SQLException {
ps.setByte(1, (byte) this.singerId);
ps.setString(2, this.firstName);
ps.setString(3, this.lastName);
ps.setBytes(4, this.singerInfo);
if (dialect == Dialect.POSTGRESQL) {
ps.setString(5, this.birthDate.toString());
} else {
ps.setDate(5, this.birthDate);
}
}
}
private static final class Album {
private final long singerId;
private final long albumId;
private final String albumTitle;
private final long marketingBudget;
private static Album of(String values) {
String[] array = values.split(",");
if (array.length != 4) {
throw new IllegalArgumentException(values);
}
return new Album(
Long.parseLong(array[0]), // singer id
Long.parseLong(array[1]), // album id
array[2].substring(1, array[2].length() - 1), // album title
Long.parseLong(array[3]) // marketing budget
);
}
private Album(long singerId, long albumId, String albumTitle, long marketingBudget) {
this.singerId = singerId;
this.albumId = albumId;
this.albumTitle = albumTitle;
this.marketingBudget = marketingBudget;
}
}
private static final class Song {
private final long singerId;
private final long albumId;
private final long songId;
private final String songName;
private final long duration;
private final String songGenre;
private static Song of(String values) {
String[] array = values.split(",");
if (array.length != 6) {
throw new IllegalArgumentException(values);
}
return new Song(
Long.parseLong(array[0]), // singer id
Long.parseLong(array[1]), // album id
Long.parseLong(array[2]), // song id
array[3].substring(1, array[3].length() - 1), // song name
Long.parseLong(array[4]), // duration
array[5].substring(1, array[5].length() - 1));
}
private Song(
long singerId,
long albumId,
long songId,
String songName,
long duration,
String songGenre) {
this.singerId = singerId;
this.albumId = albumId;
this.songId = songId;
this.songName = songName;
this.duration = duration;
this.songGenre = songGenre;
}
}
private static final class Concert {
private final long venueId;
private final long singerId;
private final Date concertDate;
private final Timestamp beginTime;
private final Timestamp endTime;
private final Long[] ticketPrices;
private static Concert of(String values) {
values = values.replaceAll("\\[(\\d+),(\\d+),(\\d+),(\\d+)]", "[$1;$2;$3;$4]");
String[] array = values.split(",");
if (array.length != 6) {
throw new IllegalArgumentException(values);
}
return new Concert(
Long.parseLong(array[0]), // venue id
Long.parseLong(array[1]), // singer id
parseDate(array[2].substring(6, array[2].length() - 1)), // concert date
parseTimestamp(array[3].substring(11, array[3].length() - 1)), // begin time
parseTimestamp(array[4].substring(11, array[4].length() - 1)), // end time
parseLongArray(array[5]) // ticket prices
);
}
private Concert(
long venueId,
long singerId,
Date concertDate,
Timestamp beginTime,
Timestamp endTime,
Long[] ticketPrices) {
this.venueId = venueId;
this.singerId = singerId;
this.concertDate = concertDate;
this.beginTime = beginTime;
this.endTime = endTime;
this.ticketPrices = ticketPrices;
}
private void setPreparedStatement(Connection connection, PreparedStatement ps, Dialect dialect)
throws SQLException {
ps.setLong(1, this.venueId);
ps.setLong(2, this.singerId);
if (dialect == Dialect.POSTGRESQL) {
ps.setString(3, this.concertDate.toString());
ps.setString(4, this.beginTime.toString());
ps.setString(5, this.endTime.toString());
} else {
ps.setDate(3, this.concertDate);
ps.setTimestamp(4, this.beginTime);
ps.setTimestamp(5, this.endTime);
ps.setArray(6, connection.createArrayOf("INT64", this.ticketPrices));
}
}
private void assertEqualsFields(Connection connection, ResultSet rs, Dialect dialect)
throws SQLException {
assertEquals(rs.getLong(1), this.venueId);
assertEquals(rs.getLong(2), this.singerId);
if (dialect == Dialect.POSTGRESQL) {
assertEquals(rs.getString(3), this.concertDate.toString());
assertEquals(rs.getString(4), this.beginTime.toString());
assertEquals(rs.getString(5), this.endTime.toString());
} else {
assertEquals(rs.getDate(3), this.concertDate);
assertEquals(rs.getTimestamp(4), this.beginTime);
assertEquals(rs.getTimestamp(5), this.endTime);
assertArrayEquals(
(Object[]) rs.getArray(6).getArray(),
(Object[]) connection.createArrayOf("INT64", this.ticketPrices).getArray());
}
}
}
private static Date parseDate(String value) {
try {
return Date.valueOf(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(value);
}
}
private static Timestamp parseTimestamp(String value) {
try {
return Timestamp.valueOf(value.replace('T', ' ').replace("Z", ""));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(value);
}
}
private static Long[] parseLongArray(String value) {
String[] values = value.substring(1, value.length() - 1).split(";");
Long[] res = new Long[values.length];
for (int index = 0; index < values.length; index++) {
res[index] = Long.valueOf(values[index]);
}
return res;
}
private static byte[] parseBytes(String value) {
return BaseEncoding.base64().decode(value);
}
private List<Singer> createSingers() {
List<Singer> res = new ArrayList<>();
for (String singerValue : readValuesFromFile("Singers.txt")) {
res.add(Singer.of(singerValue));
}
return res;
}
private List<Album> createAlbums() {
List<Album> res = new ArrayList<>();
for (String albumValue : readValuesFromFile("Albums.txt")) {
res.add(Album.of(albumValue));
}
return res;
}
private List<Song> createSongs() {
List<Song> res = new ArrayList<>();
for (String songValue : readValuesFromFile("Songs.txt")) {
res.add(Song.of(songValue));
}
return res;
}
private List<Concert> createConcerts() {
List<Concert> res = new ArrayList<>();
for (String concertValue : readValuesFromFile("Concerts.txt")) {
res.add(Concert.of(concertValue));
}
return res;
}
private String getConcertsInsertQuery(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return "INSERT INTO Concerts (VenueId, SingerId, ConcertDate, BeginTime, EndTime) VALUES (?,?,?,?,?);";
}
return "INSERT INTO Concerts (VenueId, SingerId, ConcertDate, BeginTime, EndTime, TicketPrices) VALUES (?,?,?,?,?,?);";
}
private String getConcertsInsertReturningQuery(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return "INSERT INTO Concerts (VenueId, SingerId, ConcertDate, BeginTime, EndTime) VALUES (?,?,?,?,?) RETURNING *;";
}
return "INSERT INTO Concerts (VenueId, SingerId, ConcertDate, BeginTime, EndTime, TicketPrices) VALUES (?,?,?,?,?,?) THEN RETURN *;";
}
private String getSingersInsertReturningQuery(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return "INSERT INTO Singers (SingerId, FirstName, LastName, SingerInfo, BirthDate) values (?,?,?,?,?) RETURNING *";
}
return "INSERT INTO Singers (SingerId, FirstName, LastName, SingerInfo, BirthDate) values (?,?,?,?,?) THEN RETURN *";
}
private String getAlbumsInsertReturningQuery(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return "INSERT INTO Albums (SingerId, AlbumId, AlbumTitle, MarketingBudget) VALUES (?,?,?,?) RETURNING *";
}
return "INSERT INTO Albums (SingerId, AlbumId, AlbumTitle, MarketingBudget) VALUES (?,?,?,?) THEN RETURN *";
}
private String getSongsInsertReturningQuery(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return "INSERT INTO Songs (SingerId, AlbumId, TrackId, SongName, Duration, SongGenre) VALUES (?,?,?,?,?,?) RETURNING *;";
}
return "INSERT INTO Songs (SingerId, AlbumId, TrackId, SongName, Duration, SongGenre) VALUES (?,?,?,?,?,?) THEN RETURN *;";
}
private int getConcertExpectedParamCount(Dialect dialect) {
if (dialect == Dialect.POSTGRESQL) {
return 5;
}
return 6;
}
@Test
public void test01_InsertTestData() throws SQLException {
try (Connection connection = createConnection(env, database)) {
connection.setAutoCommit(false);
try (PreparedStatement ps =
connection.prepareStatement(
"INSERT INTO Singers (SingerId, FirstName, LastName, SingerInfo, BirthDate) values (?,?,?,?,?)")) {
assertDefaultParameterMetaData(ps.getParameterMetaData(), 5);
for (Singer singer : createSingers()) {
singer.setPreparedStatement(ps, getDialect());
assertInsertSingerParameterMetadata(ps.getParameterMetaData());
ps.addBatch();
// check that adding the current params to a batch will not reset the meta data
assertInsertSingerParameterMetadata(ps.getParameterMetaData());
}
int[] results = ps.executeBatch();
for (int res : results) {
assertEquals(1, res);
}
}
try (PreparedStatement ps =
connection.prepareStatement(
"INSERT INTO Albums (SingerId, AlbumId, AlbumTitle, MarketingBudget) VALUES (?,?,?,?)")) {
assertDefaultParameterMetaData(ps.getParameterMetaData(), 4);
for (Album album : createAlbums()) {
ps.setLong(1, album.singerId);
ps.setLong(2, album.albumId);
ps.setString(3, album.albumTitle);
ps.setLong(4, album.marketingBudget);
assertInsertAlbumParameterMetadata(ps.getParameterMetaData());
assertEquals(1, ps.executeUpdate());
// check that calling executeUpdate will not reset the meta data
assertInsertAlbumParameterMetadata(ps.getParameterMetaData());
}
}
try (PreparedStatement ps =
connection.prepareStatement(
"INSERT INTO Songs (SingerId, AlbumId, TrackId, SongName, Duration, SongGenre) VALUES (?,?,?,?,?,?);")) {
assertDefaultParameterMetaData(ps.getParameterMetaData(), 6);
for (Song song : createSongs()) {
ps.setByte(1, (byte) song.singerId);
ps.setInt(2, (int) song.albumId);
ps.setShort(3, (short) song.songId);
ps.setNString(4, song.songName);
ps.setLong(5, song.duration);
ps.setCharacterStream(6, new StringReader(song.songGenre));
assertInsertSongParameterMetadata(ps.getParameterMetaData());
assertEquals(1, ps.executeUpdate());
// check that calling executeUpdate will not reset the meta data
assertInsertSongParameterMetadata(ps.getParameterMetaData());
}
}
try (PreparedStatement ps =
connection.prepareStatement(getConcertsInsertQuery(dialect.dialect))) {
assertDefaultParameterMetaData(
ps.getParameterMetaData(), getConcertExpectedParamCount(dialect.dialect));
for (Concert concert : createConcerts()) {
concert.setPreparedStatement(connection, ps, getDialect());
assertInsertConcertParameterMetadata(ps.getParameterMetaData());
assertEquals(1, ps.executeUpdate());
// check that calling executeUpdate will not reset the meta data
assertInsertConcertParameterMetadata(ps.getParameterMetaData());
}
}
connection.commit();
}
}
@Test
public void test02_VerifyTestData() throws SQLException {
try (Connection connection = createConnection(env, database)) {
try (ResultSet rs =
connection.createStatement().executeQuery("SELECT COUNT(*) FROM Singers")) {
assertTrue(rs.next());
assertEquals(30, rs.getInt(1));
assertFalse(rs.next());
}
try (ResultSet rs =
connection.createStatement().executeQuery("SELECT COUNT(*) FROM Albums")) {
assertTrue(rs.next());
assertEquals(60, rs.getByte(1));
assertFalse(rs.next());
}
try (ResultSet rs = connection.createStatement().executeQuery("SELECT COUNT(*) FROM Songs")) {
assertTrue(rs.next());
assertEquals(149, rs.getShort(1));
assertFalse(rs.next());
}
try (ResultSet rs =
connection.createStatement().executeQuery("SELECT COUNT(*) FROM Concerts")) {
assertTrue(rs.next());
assertEquals(100L, rs.getLong(1));
assertFalse(rs.next());
}
try (PreparedStatement ps =
connection.prepareStatement("SELECT * FROM Concerts WHERE VenueId=? AND SingerId=?")) {
ps.setLong(1, 1L);
ps.setLong(2, 1L);
// Expected:
// (1,1,DATE '2003-06-19',TIMESTAMP '2003-06-19T12:30:05Z',TIMESTAMP
// '2003-06-19T18:57:15Z',[11,93,140,923]);
try (ResultSet rs = ps.executeQuery()) {
assertTrue(rs.next());
assertEquals(1L, rs.getLong(1));
assertEquals(1L, rs.getLong(2));
if (dialect.dialect == Dialect.POSTGRESQL) {
assertEquals("2003-06-19", rs.getString(3));
assertEquals("2003-06-19 12:30:05.0", rs.getString(4));
assertEquals("2003-06-19 18:57:15.0", rs.getString(5));
} else {
assertEquals(Date.valueOf("2003-06-19"), rs.getDate(3));
assertEquals(Timestamp.valueOf("2003-06-19 12:30:05"), rs.getTimestamp(4));
assertEquals(Timestamp.valueOf("2003-06-19 18:57:15"), rs.getTimestamp(5));
assertArrayEquals(
new Long[] {11L, 93L, 140L, 923L}, (Long[]) rs.getArray(6).getArray());
}
}
}
}
}
@SuppressWarnings("deprecation")
@Test
public void test03_Dates() throws SQLException {
assumeFalse(
"Date type is not supported on POSTGRESQL dialect", dialect.dialect == Dialect.POSTGRESQL);
List<String> expectedValues = new ArrayList<>();
expectedValues.add("2008-01-01");
expectedValues.add("2000-01-01");
expectedValues.add("1900-01-01");
expectedValues.add("2000-02-29");
expectedValues.add("2004-02-29");
expectedValues.add("2018-12-31");
expectedValues.add("2015-11-15");
expectedValues.add("2015-11-15");
expectedValues.add("2015-11-15");
List<Date> testDates = new ArrayList<>();
testDates.add(Date.valueOf("2008-01-01"));
testDates.add(Date.valueOf("2000-01-01"));
testDates.add(Date.valueOf("1900-01-01"));
testDates.add(Date.valueOf("2000-02-29"));
testDates.add(Date.valueOf("2004-02-29"));
testDates.add(Date.valueOf("2018-12-31"));
// Cloud Spanner does not store any timezone information, meaning that it shouldn't matter in
// what timezone a date is sent to Cloud Spanner, the same date in the local timezone (or the
// requested timezone) should be returned.
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.clear();
cal.set(2015, Calendar.NOVEMBER, 15, 10, 0, 0);
testDates.add(new Date(cal.getTimeInMillis()));
cal = Calendar.getInstance(TimeZone.getTimeZone("CET"));
cal.clear();
cal.set(2015, Calendar.NOVEMBER, 15, 10, 0, 0);
testDates.add(new Date(cal.getTimeInMillis()));
cal = Calendar.getInstance(TimeZone.getTimeZone("PST"));
cal.clear();
cal.set(2015, Calendar.NOVEMBER, 15, 10, 0, 0);
testDates.add(new Date(cal.getTimeInMillis()));
List<Calendar> calendars = new ArrayList<>();
calendars.add(null);
calendars.add(Calendar.getInstance());
calendars.add(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
calendars.add(Calendar.getInstance(TimeZone.getTimeZone("CET")));
calendars.add(Calendar.getInstance(TimeZone.getTimeZone("PST")));
try (Connection connection = createConnection(env, database)) {
for (Calendar testCalendar : calendars) {
int index = 0;
for (Date testDate : testDates) {
try (PreparedStatement ps =
connection.prepareStatement(
"INSERT INTO Concerts (VenueId, SingerId, ConcertDate, BeginTime, EndTime, TicketPrices) VALUES (?,?,?,?,?,?);")) {
assertDefaultParameterMetaData(ps.getParameterMetaData(), 6);
ps.setLong(1, 100);
ps.setLong(2, 19);
ps.setDate(3, testDate);
ps.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
ps.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
ps.setArray(6, connection.createArrayOf("INT64", new Long[] {}));
ps.executeUpdate();
}
try (PreparedStatement ps =
connection.prepareStatement(
"SELECT * FROM Concerts WHERE VenueId=? AND SingerId=?")) {
ps.setLong(1, 100L);
ps.setLong(2, 19L);
try (ResultSet rs = ps.executeQuery()) {
assertTrue(rs.next());
if (testCalendar == null) {
assertEquals(Date.valueOf(expectedValues.get(index)), rs.getDate(3));
} else {
// Parse the date in the local timezone.
Date date = Date.valueOf(expectedValues.get(index));
// Create a calendar in the test timezone with only the date part set.
Calendar localCalendar = Calendar.getInstance(testCalendar.getTimeZone());
localCalendar.clear();
localCalendar.set(date.getYear() + 1900, date.getMonth(), date.getDate());
// Check that the actual time of the date returned by the ResultSet is equal to the
// local time in the timezone of the Calendar that is used.
assertEquals(
new Date(localCalendar.getTimeInMillis()), rs.getDate(3, testCalendar));
}
}
}
connection
.createStatement()
.execute("DELETE FROM Concerts WHERE VenueId=100 AND SingerId=19");
index++;
}
}
}
}
@Test
public void test04_Timestamps() throws SQLException {
assumeFalse(
"Timestamp type is not supported on POSTGRESQL dialect",
dialect.dialect == Dialect.POSTGRESQL);
List<String> expectedValues = new ArrayList<>();
expectedValues.add("2008-01-01 10:00:00");
expectedValues.add("2000-01-01 00:00:00");
expectedValues.add("1900-01-01 12:13:14");
expectedValues.add("2000-02-29 02:00:00");
expectedValues.add("2004-02-29 03:00:00");
expectedValues.add("2018-12-31 23:59:59");
expectedValues.add("2015-11-15 10:00:00");
expectedValues.add("2015-11-15 10:00:00");
expectedValues.add("2015-11-15 10:00:00");
List<Timestamp> testTimestamps = new ArrayList<>();
testTimestamps.add(Timestamp.valueOf(expectedValues.get(0)));
testTimestamps.add(Timestamp.valueOf(expectedValues.get(1)));
testTimestamps.add(Timestamp.valueOf(expectedValues.get(2)));
testTimestamps.add(Timestamp.valueOf(expectedValues.get(3)));
testTimestamps.add(Timestamp.valueOf(expectedValues.get(4)));
testTimestamps.add(Timestamp.valueOf(expectedValues.get(5)));
// Cloud Spanner does not store any timezone information, but does store the timestamp in UTC
// format.
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.clear();
cal.set(2015, Calendar.NOVEMBER, 15);
testTimestamps.add(new Timestamp(cal.getTimeInMillis()));
cal = Calendar.getInstance(TimeZone.getTimeZone("CET"));
cal.clear();
cal.set(2015, Calendar.NOVEMBER, 15);
testTimestamps.add(new Timestamp(cal.getTimeInMillis()));
cal = Calendar.getInstance(TimeZone.getTimeZone("PST"));
cal.clear();
cal.set(2015, Calendar.NOVEMBER, 15);
testTimestamps.add(new Timestamp(cal.getTimeInMillis()));
List<Calendar> calendars = new ArrayList<>();
calendars.add(null);
calendars.add(Calendar.getInstance());
calendars.add(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
calendars.add(Calendar.getInstance(TimeZone.getTimeZone("CET")));
calendars.add(Calendar.getInstance(TimeZone.getTimeZone("PST")));
try (Connection connection = createConnection(env, database)) {
for (Calendar testCalendar : calendars) {
for (Timestamp testTimestamp : testTimestamps) {
try (PreparedStatement ps =
connection.prepareStatement(
"INSERT INTO Concerts (VenueId, SingerId, ConcertDate, BeginTime, EndTime, TicketPrices) VALUES (?,?,?,?,?,?);")) {
assertDefaultParameterMetaData(ps.getParameterMetaData(), 6);
ps.setLong(1, 100);
ps.setLong(2, 19);
ps.setDate(3, new Date(System.currentTimeMillis()));
// Cloud Spanner will store the timestamp in UTC and no other timezone information.
ps.setTimestamp(4, testTimestamp);
ps.setTimestamp(5, testTimestamp, testCalendar);
ps.setArray(6, connection.createArrayOf("INT64", new Long[] {}));
ps.executeUpdate();
}
try (PreparedStatement ps =
connection.prepareStatement(
"SELECT * FROM Concerts WHERE VenueId=? AND SingerId=?")) {
ps.setLong(1, 100L);
ps.setLong(2, 19L);
try (ResultSet rs = ps.executeQuery()) {
assertTrue(rs.next());
// First test the timestamp that was sent to Spanner using the default timezone.
// Get the timestamp in the default timezone.
Timestamp inDefaultTZ = rs.getTimestamp(4);
assertEquals(testTimestamp.getTime(), inDefaultTZ.getTime());
// Then get it in the test timezone.
if (testCalendar != null) {
Timestamp inOtherTZ = rs.getTimestamp(4, testCalendar);
assertEquals(
testTimestamp.getTime() + testCalendar.getTimeZone().getRawOffset(),
inOtherTZ.getTime());
}
// Then test the timestamp that was sent to Spanner using a specific timezone.
// Get the timestamp in the default timezone.
inDefaultTZ = rs.getTimestamp(5);
if (testCalendar == null) {
assertEquals(testTimestamp.getTime(), inDefaultTZ.getTime());
} else {
assertEquals(
testTimestamp.getTime() - testCalendar.getTimeZone().getRawOffset(),
inDefaultTZ.getTime());
}
// Then get it in the test timezone.
if (testCalendar != null) {
Timestamp inOtherTZ = rs.getTimestamp(5, testCalendar);
assertEquals(testTimestamp.getTime(), inOtherTZ.getTime());
}
}
}
connection
.createStatement()
.execute("DELETE FROM Concerts WHERE VenueId=100 AND SingerId=19");
}
}
}
}
@Test
public void test05_BatchUpdates() throws SQLException {
for (boolean autocommit : new boolean[] {true, false}) {
try (Connection con1 = createConnection(env, database);
Connection con2 = createConnection(env, database)) {
con1.setAutoCommit(autocommit);
int[] updateCounts;
String[] params = new String[] {"A%", "B%", "C%"};
try (PreparedStatement ps =
con1.prepareStatement("UPDATE Singers SET FirstName=LastName WHERE LastName LIKE ?")) {
for (String param : params) {
ps.setString(1, param);
ps.addBatch();
}
updateCounts = ps.executeBatch();
}
assertEquals(params.length, updateCounts.length);
long totalUpdated = 0;
try (PreparedStatement ps =
con1.prepareStatement("SELECT COUNT(*) FROM Singers WHERE LastName LIKE ?")) {
for (int i = 0; i < updateCounts.length; i++) {
ps.setString(1, params[i]);
try (ResultSet rs = ps.executeQuery()) {
assertTrue(rs.next());
assertEquals(rs.getInt(1), updateCounts[i]);
totalUpdated += updateCounts[i];
}
}
}
// Check whether the updated values are readable on the second connection.
try (ResultSet rs =
con2.createStatement()
.executeQuery("SELECT COUNT(*) FROM Singers WHERE FirstName=LastName")) {
assertTrue(rs.next());
if (autocommit) {
assertEquals(totalUpdated, rs.getLong(1));
} else {
assertEquals(0, rs.getLong(1));
}
}
// If not in autocommit mode --> commit and verify.
if (!autocommit) {
con1.commit();
try (ResultSet rs =
con2.createStatement()
.executeQuery("SELECT COUNT(*) FROM Singers WHERE FirstName=LastName")) {
assertTrue(rs.next());
assertEquals(totalUpdated, rs.getLong(1));
}
}
// Set first names to null for the updated records for the next test run.
int updateCount =
con2.createStatement()
.executeUpdate("UPDATE Singers SET FirstName=null WHERE FirstName=LastName");
assertEquals(totalUpdated, updateCount);
}
}
}
@Test
public void test06_BatchUpdatesWithException() throws SQLException {
for (boolean autocommit : new boolean[] {true, false}) {
try (Connection con1 = createConnection(env, database);
Connection con2 = createConnection(env, database)) {
con1.setAutoCommit(autocommit);
String[] params = new String[] {"A%", "B%", "C%", "D%"};
// Statement number three will fail because the value is too long for the column.
int[] updateValues = new int[] {1, 1, 1024, 1};
try (PreparedStatement ps =
con1.prepareStatement("UPDATE Singers SET FirstName=? WHERE LastName LIKE ?")) {
for (int i = 0; i < params.length; i++) {
ps.setString(1, Strings.repeat("not too long", updateValues[i]));
ps.setString(2, params[i]);
ps.addBatch();
}
ps.executeBatch();
fail("missing expected BatchUpdateException");
} catch (BatchUpdateException e) {
assertEquals(2, e.getUpdateCounts().length);
}
// If not in autocommit mode --> rollback before the next run.
if (!autocommit) {
con1.rollback();
}
// Set first names to null for the updated records for the next test run.
try (PreparedStatement ps =
con2.prepareStatement("UPDATE Singers SET FirstName=null WHERE FirstName=?")) {
ps.setString(1, "not too long");
}
}
}
}
@Test
public void test07_StatementBatchUpdateWithException() throws SQLException {
try (Connection con = createConnection(env, database)) {
// The following statements will fail because the value is too long.
try (Statement statement = con.createStatement()) {
statement.addBatch(
String.format(
"UPDATE Singers SET FirstName='%s' WHERE LastName LIKE 'A%%'",
Strings.repeat("too long", 1024)));
statement.addBatch(
String.format(
"UPDATE Singers SET FirstName='%s' WHERE LastName LIKE 'B%%'",
Strings.repeat("too long", 1024)));
statement.executeBatch();
fail("missing expected BatchUpdateException");
} catch (BatchUpdateException e) {
assertNotNull(e.getUpdateCounts());
}
// The following statements will fail because the table does not exist.
try (Statement statement = con.createStatement()) {
statement.addBatch(
String.format(
"UPDATE Non_Existent_Table SET FirstName='%s' WHERE LastName LIKE 'A%%'",
Strings.repeat("too long", 1024)));
statement.addBatch(
String.format(
"UPDATE Non_Existent_Table SET FirstName='%s' WHERE LastName LIKE 'B%%'",
Strings.repeat("too long", 1024)));
statement.executeBatch();
fail();
} catch (BatchUpdateException e) {
assertNotNull(e.getUpdateCounts());
}
// The following statements will fail because the primary key values conflict.
try (Statement statement = con.createStatement()) {
statement.addBatch(
"INSERT INTO Singers (SingerId, FirstName, LastName, SingerInfo, BirthDate) VALUES (9999, 'Test', 'Test', NULL, NULL)");
statement.addBatch(
"INSERT INTO Singers (SingerId, FirstName, LastName, SingerInfo, BirthDate) VALUES (9999, 'Test', 'Test', NULL, NULL)");
statement.executeBatch();
fail();
} catch (BatchUpdateException e) {
assertNotNull(e.getUpdateCounts());
}
}
}
@Test
public void test08_InsertAllColumnTypes() throws SQLException {
assumeFalse(
"TableWithAllColumnTypes type is not supported on POSTGRESQL dialect",
dialect.dialect == Dialect.POSTGRESQL);
String sql =
"INSERT INTO TableWithAllColumnTypes ("
+ "ColInt64, ColFloat64, ColBool, ColString, ColStringMax, ColBytes, ColBytesMax, ColDate, ColTimestamp, ColCommitTS, ColNumeric, ColJson, "
+ "ColInt64Array, ColFloat64Array, ColBoolArray, ColStringArray, ColStringMaxArray, ColBytesArray, ColBytesMaxArray, ColDateArray, ColTimestampArray, ColNumericArray, ColJsonArray"
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, PENDING_COMMIT_TIMESTAMP(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (Connection con = createConnection(env, database)) {
try (PreparedStatement ps = con.prepareStatement(sql)) {
int index = 0;
ps.setLong(++index, 1L);
ps.setDouble(++index, 2D);
ps.setBoolean(++index, true);
ps.setString(++index, "test");
ps.setObject(++index, UUID.fromString("2d37f522-e0a5-4f22-8e09-4d77d299c967"));
ps.setBytes(++index, "test".getBytes());
ps.setBytes(++index, "testtest".getBytes());
ps.setDate(++index, new Date(System.currentTimeMillis()));
ps.setTimestamp(++index, new Timestamp(System.currentTimeMillis()));
ps.setBigDecimal(++index, BigDecimal.TEN);
ps.setObject(++index, "{\"test_value\": \"foo\"}", JsonType.INSTANCE);
ps.setArray(++index, con.createArrayOf("INT64", new Long[] {1L, 2L, 3L}));
ps.setArray(++index, con.createArrayOf("FLOAT64", new Double[] {1.1D, 2.2D, 3.3D}));
ps.setArray(
++index, con.createArrayOf("BOOL", new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}));
ps.setArray(++index, con.createArrayOf("STRING", new String[] {"1", "2", "3"}));
ps.setArray(++index, con.createArrayOf("STRING", new String[] {"3", "2", "1"}));
ps.setArray(
++index,
con.createArrayOf(
"BYTES", new byte[][] {"1".getBytes(), "2".getBytes(), "3".getBytes()}));
ps.setArray(
++index,
con.createArrayOf(
"BYTES", new byte[][] {"333".getBytes(), "222".getBytes(), "111".getBytes()}));
ps.setArray(
++index,
con.createArrayOf(
"DATE", new Date[] {new Date(System.currentTimeMillis()), null, new Date(0)}));
ps.setArray(
++index,
con.createArrayOf(
"TIMESTAMP",
new Timestamp[] {
new Timestamp(System.currentTimeMillis()), null, new Timestamp(0)
}));
ps.setArray(
++index,
con.createArrayOf("NUMERIC", new BigDecimal[] {BigDecimal.ONE, null, BigDecimal.TEN}));
ps.setArray(
++index,
con.createArrayOf(
"JSON", new String[] {"{\"test_value\": \"foo\"}", "{}", "[]", null}));
assertEquals(1, ps.executeUpdate());
}
try (ResultSet rs =
con.createStatement().executeQuery("SELECT * FROM TableWithAllColumnTypes")) {
int index = 0;
assertTrue(rs.next());
assertEquals(1L, rs.getLong(++index));
assertEquals(2d, rs.getDouble(++index), 0.0d);
assertTrue(rs.getBoolean(++index));
assertEquals("test", rs.getString(++index));
assertEquals("2d37f522-e0a5-4f22-8e09-4d77d299c967", rs.getString(++index));
assertArrayEquals("test".getBytes(), rs.getBytes(++index));
assertArrayEquals("testtest".getBytes(), rs.getBytes(++index));
assertNotNull(rs.getDate(++index));
assertNotNull(rs.getTimestamp(++index));
assertNotNull(rs.getTime(++index)); // Commit timestamp
assertEquals(BigDecimal.TEN, rs.getBigDecimal(++index));
assertEquals("{\"test_value\":\"foo\"}", rs.getString(++index));
assertArrayEquals(new Long[] {1L, 2L, 3L}, (Long[]) rs.getArray(++index).getArray());
assertArrayEquals(
new Double[] {1.1D, 2.2D, 3.3D}, (Double[]) rs.getArray(++index).getArray());
assertArrayEquals(
new Boolean[] {true, null, false}, (Boolean[]) rs.getArray(++index).getArray());
assertArrayEquals(new String[] {"1", "2", "3"}, (String[]) rs.getArray(++index).getArray());
assertArrayEquals(new String[] {"3", "2", "1"}, (String[]) rs.getArray(++index).getArray());
assertArrayEquals(
new byte[][] {"1".getBytes(), "2".getBytes(), "3".getBytes()},
(byte[][]) rs.getArray(++index).getArray());
assertArrayEquals(
new byte[][] {"333".getBytes(), "222".getBytes(), "111".getBytes()},
(byte[][]) rs.getArray(++index).getArray());
assertEquals(3, ((Date[]) rs.getArray(++index).getArray()).length);
assertEquals(3, ((Timestamp[]) rs.getArray(++index).getArray()).length);
assertArrayEquals(
new BigDecimal[] {BigDecimal.ONE, null, BigDecimal.TEN},
(BigDecimal[]) rs.getArray(++index).getArray());
assertArrayEquals(
new String[] {"{\"test_value\":\"foo\"}", "{}", "[]", null},
(String[]) rs.getArray(++index).getArray());
assertFalse(rs.next());
}
}
}
@Test
public void test08_PGInsertAllColumnTypes() throws SQLException {
assumeTrue(dialect.dialect == Dialect.POSTGRESQL);
String sql =
"INSERT INTO TableWithAllColumnTypes ("
+ "ColInt64, ColFloat64, ColBool, ColString, ColStringMax, ColBytes, ColDate, ColTimestamp, ColNumeric, ColJson"
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (Connection con = createConnection(env, database)) {
try (PreparedStatement ps = con.prepareStatement(sql)) {
int index = 0;
ps.setLong(++index, 1L);
ps.setDouble(++index, 2D);
ps.setBoolean(++index, true);
ps.setString(++index, "test");
ps.setObject(++index, UUID.fromString("2d37f522-e0a5-4f22-8e09-4d77d299c967"));
ps.setBytes(++index, "test".getBytes());
ps.setDate(++index, new Date(System.currentTimeMillis()));
ps.setTimestamp(++index, new Timestamp(System.currentTimeMillis()));
ps.setBigDecimal(++index, BigDecimal.TEN);
// TODO: This test currently uses string/varchar. This should be updated to JSONB.
ps.setObject(++index, "{\"test_value\": \"foo\"}", Types.VARCHAR);
assertEquals(1, ps.executeUpdate());
}
try (ResultSet rs =
con.createStatement().executeQuery("SELECT * FROM TableWithAllColumnTypes")) {
int index = 0;
assertTrue(rs.next());
assertEquals(1L, rs.getLong(++index));
assertEquals(2d, rs.getDouble(++index), 0.0d);
assertTrue(rs.getBoolean(++index));
assertEquals("test", rs.getString(++index));
assertEquals("2d37f522-e0a5-4f22-8e09-4d77d299c967", rs.getString(++index));
assertArrayEquals("test".getBytes(), rs.getBytes(++index));
assertNotNull(rs.getDate(++index));
assertNotNull(rs.getTimestamp(++index));
assertEquals(BigDecimal.TEN, rs.getBigDecimal(++index));
assertEquals("{\"test_value\": \"foo\"}", rs.getString(++index));