forked from kokosing/trino-rest
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Sync.java
1937 lines (1799 loc) · 95.2 KB
/
Sync.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
/*
* 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 pl.net.was.rest.github;
import com.google.common.collect.ImmutableList;
import java.net.NoRouteToHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.google.common.base.Throwables.getRootCause;
import static java.lang.String.format;
import static java.lang.System.exit;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class Sync
{
private static final Logger log;
static {
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1$tF %1$tT %4$s %2$s %5$s%6$s%n");
log = Logger.getLogger(Sync.class.getName());
}
private Sync() {}
public static void main(String[] args)
{
String url = "jdbc:trino://localhost:8080/github/default";
String username = "admin";
String password = "";
Map<String, String> env = System.getenv();
// TODO combine with System.Properties
List<String> names = Arrays.asList(
"GITHUB_OWNER",
"GITHUB_REPO",
"SYNC_TABLES",
"LOG_LEVEL",
"TRINO_DEST_SCHEMA",
"TRINO_SRC_SCHEMA",
"TRINO_URL",
"TRINO_USERNAME",
"TRINO_PASSWORD",
"EMPTY_INSERT_LIMIT",
"CHECK_STEPS_DUPLICATES",
"CHECK_ARTIFACTS_DUPLICATES",
"QUERY_DELAY_MS");
Map<String, String> defaults = Map.of(
"TRINO_URL", url,
"TRINO_USERNAME", username,
"TRINO_PASSWORD", password,
// notice that jog_logs and artifacts are not enabled by default
"SYNC_TABLES", "repos,commits,issues,issue_comments,pulls,pull_commits,review_comments,reviews,workflows,runs,jobs,steps,check_suites,check_runs,check_run_annotations",
"LOG_LEVEL", "INFO",
"EMPTY_INSERT_LIMIT", "1",
"CHECK_STEPS_DUPLICATES", "false",
"CHECK_ARTIFACTS_DUPLICATES", "false",
"QUERY_DELAY_MS", "0");
for (String name : names) {
String value = env.getOrDefault(name, defaults.getOrDefault(name, ""));
if (!value.isEmpty() && name.equals("TRINO_PASSWORD")) {
value = "***";
}
log.info(format("%s=%s", name, value));
}
if (env.containsKey("TRINO_URL")) {
url = env.get("TRINO_URL");
}
if (env.containsKey("TRINO_USERNAME")) {
username = env.get("TRINO_USERNAME");
}
if (env.containsKey("TRINO_PASSWORD")) {
password = env.get("TRINO_PASSWORD");
}
String owner = System.getenv("GITHUB_OWNER");
String repo = System.getenv("GITHUB_REPO");
String destSchema = System.getenv("TRINO_DEST_SCHEMA");
String srcSchema = System.getenv("TRINO_SRC_SCHEMA");
String tables = System.getenv("SYNC_TABLES");
if (tables == null) {
tables = defaults.get("SYNC_TABLES");
}
Set<String> enabledTables = new LinkedHashSet<>(Arrays.asList(tables.split(",")));
Level level = Level.parse(Optional.ofNullable(System.getenv("LOG_LEVEL")).orElse("INFO"));
Logger root = Logger.getLogger("");
for (Handler h : root.getHandlers()) {
h.setLevel(level);
}
log.setLevel(level);
root.setLevel(level);
Logger.getLogger("jdk.internal").setLevel(Level.INFO);
requireNonNull(owner, "GITHUB_OWNER environmental variable must be set");
requireNonNull(repo, "GITHUB_REPO environmental variable must be set");
requireNonNull(destSchema, "TRINO_DEST_SCHEMA environmental variable must be set");
requireNonNull(srcSchema, "TRINO_SRC_SCHEMA environmental variable must be set");
Options options = new Options(null, owner, repo, destSchema, srcSchema);
// Note that the order in which these functions are called is determined by enabledTables, not availableTables
Map<String, Function<Options, Boolean>> availableTables = new LinkedHashMap<>();
availableTables.put("repos", Sync::syncRepos);
availableTables.put("commits", Sync::syncCommits);
availableTables.put("issues", Sync::syncIssues);
availableTables.put("issue_comments", Sync::syncIssueComments);
availableTables.put("pulls", Sync::syncPulls);
availableTables.put("pull_commits", Sync::syncPullCommits);
availableTables.put("pull_stats", Sync::syncPullStats);
availableTables.put("reviews", Sync::syncReviews);
availableTables.put("review_comments", Sync::syncReviewComments);
availableTables.put("workflows", Sync::syncWorkflows);
availableTables.put("runs", Sync::syncRuns);
availableTables.put("jobs", Sync::syncJobs);
availableTables.put("job_logs", Sync::syncJobLogs);
availableTables.put("steps", Sync::syncSteps);
availableTables.put("artifacts", Sync::syncArtifacts);
availableTables.put("check_suites", Sync::syncCheckSuites);
availableTables.put("check_runs", Sync::syncCheckRuns);
availableTables.put("check_run_annotations", Sync::syncCheckRunAnnotations);
availableTables.put("teams", Sync::syncTeams);
availableTables.put("members", Sync::syncMembers);
availableTables.put("collaborators", Sync::syncCollaborators);
boolean result = true;
try (Connection conn = DriverManager.getConnection(url, username, password)) {
options.conn = conn;
for (String table : enabledTables) {
Function<Options, Boolean> syncFunc = availableTables.get(table);
if (syncFunc == null) {
throw new IllegalArgumentException(format(
"Unknown table %s, must be one of: %s",
table,
String.join(", ", availableTables.keySet())));
}
result = syncFunc.apply(options) && result;
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
}
exit(!result ? 1 : 0);
}
private static class Options
{
Connection conn;
String owner;
String repo;
String destSchema;
String srcSchema;
public Options(Connection conn, String owner, String repo, String destSchema, String srcSchema)
{
this.conn = conn;
this.owner = owner;
this.repo = repo;
this.destSchema = destSchema;
this.srcSchema = srcSchema;
}
}
private static boolean syncRepos(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
// sync all columns except permissions because not all connectors support maps and permissions only apply to currently used token anyway
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".repos AS SELECT " +
"id, name, full_name, owner_id, owner_login, private, description, fork, homepage, url, forks_count, stargazers_count, watchers_count, size, default_branch, open_issues_count, " +
"is_template, topics, has_issues, has_projects, has_wiki, has_pages, has_downloads, archived, disabled, visibility, pushed_at, created_at, updated_at " +
"FROM " + srcSchema + ".repos WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON repos(id);
// CREATE INDEX ON repos(name);
// CREATE INDEX ON repos(full_name);
// CREATE INDEX ON repos(owner_id);
// CREATE INDEX ON repos(owner_login);
// note that the first one is NOT a primary key, so updated records can be inserted
// and then removed as duplicates by running this in the target database (not supported in Trino):
// DELETE FROM repos a USING repos b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// or use the unique_repos view (from `trino-rest-github/sql/views.sql`) that ignores duplicates
// there's no "since" filter, but we can sort by updated_at, so keep inserting records where this is greater than max
PreparedStatement lastUpdatedStatement = conn.prepareStatement(
"SELECT COALESCE(MAX(updated_at), TIMESTAMP '0000-01-01') AS latest FROM " + destSchema + ".repos WHERE owner_login = ?");
lastUpdatedStatement.setString(1, options.owner);
ResultSet result = lastUpdatedStatement.executeQuery();
result.next();
String lastUpdated = result.getString(1);
PreparedStatement statement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".repos " +
"SELECT " +
"id, name, full_name, owner_id, owner_login, private, description, fork, homepage, url, forks_count, stargazers_count, watchers_count, size, default_branch, open_issues_count, " +
"is_template, topics, has_issues, has_projects, has_wiki, has_pages, has_downloads, archived, disabled, visibility, pushed_at, created_at, updated_at " +
"FROM repos WHERE owner_login = ? AND updated_at > CAST(? AS TIMESTAMP)");
statement.setString(1, options.owner);
statement.setString(2, lastUpdated);
log.info("Fetching repos");
long startTime = System.currentTimeMillis();
int rows = retryExecute(statement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncCommits(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".commits AS SELECT * FROM " + srcSchema + ".commits WITH NO DATA");
// consider adding some indexes:
// ALTER TABLE runs ADD PRIMARY KEY (owner, repo, sha);
syncSince(options, "commits", "committer_date");
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncIssues(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".issues AS SELECT * FROM " + srcSchema + ".issues WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON issues(owner, repo);
// CREATE INDEX ON issues(id);
// CREATE INDEX ON issues(user_id);
// CREATE INDEX ON issues(milestone_id);
// CREATE INDEX ON issues(assignee_id);
// CREATE INDEX ON issues(state);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using a procedure
// DELETE FROM issues a USING issues b WHERE a.updated_at < b.updated_at AND a.id = b.id;
syncSince(options, "issues");
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncIssueComments(Options options)
{
try {
options.conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + options.destSchema + ".issue_comments AS SELECT * FROM " + options.srcSchema + ".issue_comments WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON issue_comments(owner, repo);
// CREATE INDEX ON issue_comments(id);
// CREATE INDEX ON issue_comments(user_id);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using a procedure
// DELETE FROM issue_comments a USING issue_comments b WHERE a.updated_at < b.updated_at AND a.id = b.id;
try {
syncSince(options, "issue_comments");
}
catch (Exception e) {
// fetching comments since the epoch can fail with a Server Error, so fall back to fetching them for every issue and pull request
// TODO how to distinguish rate limit errors?
log.severe("Failed to get latest updated issue comments, falling back to checking every issue and pull request: " + e.getMessage());
syncAllIssueComments(options);
syncAllPullComments(options);
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncAllIssueComments(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".issue_comments AS SELECT * FROM " + srcSchema + ".issue_comments WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON issue_comments(owner, repo);
// CREATE INDEX ON issue_comments(id);
// CREATE INDEX ON issue_comments(user_id);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using a procedure
// DELETE FROM issue_comments a USING issue_comments b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// only fetch issue comments from up to 30 issues without any comments
String runsQuery = format(
"SELECT r.id, r.number " +
"FROM " + destSchema + ".issues r " +
"LEFT JOIN " + destSchema + ".issue_comments c ON c.issue_url = r.url " +
"WHERE r.owner = ? AND r.repo = ? AND r.id > ? " +
"GROUP BY r.id, r.number " +
"HAVING COUNT(c.id) = 0 " +
"ORDER BY r.id ASC LIMIT %d", 30);
// since there's no difference between issues without comments and those we have not checked or yet,
// we need to know the last checked issue id and add a condition to fetch lesser numbers
PreparedStatement idStatement = conn.prepareStatement("SELECT max(r.id) FROM (" + runsQuery + ") r");
idStatement.setString(1, options.owner);
idStatement.setString(2, options.repo);
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".issue_comments " +
"SELECT src.* " +
"FROM (" + runsQuery + ") r " +
"CROSS JOIN unnest(issue_comments(?, ?, r.number)) src " +
"LEFT JOIN " + destSchema + ".issue_comments dst ON dst.id = src.id " +
"WHERE dst.id IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(4, options.owner);
insertStatement.setString(5, options.repo);
long previousId = 0;
while (true) {
insertStatement.setLong(3, previousId);
log.info(format("Fetching comments for issues with id greater than %d", previousId));
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
idStatement.setLong(3, previousId);
log.info("Checking for next issues without comments");
ResultSet resultSet = idStatement.executeQuery();
if (!resultSet.next()) {
break;
}
previousId = resultSet.getLong(1);
if (resultSet.wasNull()) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncAllPullComments(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".issue_comments AS SELECT * FROM " + srcSchema + ".issue_comments WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON issue_comments(owner, repo);
// CREATE INDEX ON issue_comments(id);
// CREATE INDEX ON issue_comments(user_id);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using a procedure
// DELETE FROM issue_comments a USING issue_comments b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// only fetch pull comments from up to 30 pulls without any comments
String runsQuery = format(
"SELECT r.id, r.number " +
"FROM " + destSchema + ".pulls r " +
"LEFT JOIN " + destSchema + ".issue_comments c ON c.issue_url = r.url " +
"WHERE r.owner = ? AND r.repo = ? AND r.id > ? " +
"GROUP BY r.id, r.number " +
"HAVING COUNT(c.id) = 0 " +
"ORDER BY r.id ASC LIMIT %d", 30);
// since there's no difference between pulls without comments and those we have not checked or yet,
// we need to know the last checked pull id and add a condition to fetch lesser numbers
PreparedStatement idStatement = conn.prepareStatement("SELECT max(r.id) FROM (" + runsQuery + ") r");
idStatement.setString(1, options.owner);
idStatement.setString(2, options.repo);
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".issue_comments " +
"SELECT src.* " +
"FROM (" + runsQuery + ") r " +
"CROSS JOIN unnest(issue_comments(?, ?, r.number)) src " +
"LEFT JOIN " + destSchema + ".issue_comments dst ON dst.id = src.id " +
"WHERE dst.id IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(4, options.owner);
insertStatement.setString(5, options.repo);
long previousId = 0;
while (true) {
insertStatement.setLong(3, previousId);
log.info(format("Fetching comments for pulls with id greater than %d", previousId));
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
idStatement.setLong(3, previousId);
log.info("Checking for next pulls without comments");
ResultSet resultSet = idStatement.executeQuery();
if (!resultSet.next()) {
break;
}
previousId = resultSet.getLong(1);
if (resultSet.wasNull()) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncReviewComments(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".review_comments AS SELECT * FROM " + srcSchema + ".review_comments WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON review_comments(id);
// CREATE INDEX ON review_comments(owner, repo);
// CREATE INDEX ON review_comments(user_id);
// CREATE INDEX ON review_comments(pull_request_review_id);
// CREATE INDEX ON review_comments(in_reply_to_id);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using a procedure
// DELETE FROM review_comments a USING review_comments b WHERE a.updated_at < b.updated_at AND a.id = b.id;
try {
return syncSince(options, "review_comments");
}
catch (Exception e) {
// fetching comments since the epoch can fail with a Server Error, so fall back to fetching them for every review
// TODO how to distinguish rate limit errors?
log.severe("Failed to get latest updated review comments, falling back to checking every review: " + e.getMessage());
return syncAllReviewComments(options);
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
}
private static boolean syncAllReviewComments(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".review_comments AS SELECT * FROM " + srcSchema + ".review_comments WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON review_comments(id);
// CREATE INDEX ON review_comments(owner, repo);
// CREATE INDEX ON review_comments(user_id);
// CREATE INDEX ON review_comments(pull_request_review_id);
// CREATE INDEX ON review_comments(in_reply_to_id);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using a procedure
// DELETE FROM review_comments a USING review_comments b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// only fetch review comments from up to 30 reviews without any comments
String runsQuery = format(
"SELECT r.id, r.pull_number " +
"FROM " + destSchema + ".reviews r " +
"LEFT JOIN " + destSchema + ".review_comments c ON c.pull_request_review_id = r.id " +
"WHERE r.owner = ? AND r.repo = ? AND r.id > ? " +
"GROUP BY r.id, r.pull_number " +
"HAVING COUNT(c.id) = 0 " +
"ORDER BY r.id ASC LIMIT %d", 30);
// since there's no difference between reviews without comments and those we have not checked or yet,
// we need to know the last checked review id and add a condition to fetch lesser numbers
PreparedStatement idStatement = conn.prepareStatement("SELECT max(r.id) FROM (" + runsQuery + ") r");
idStatement.setString(1, options.owner);
idStatement.setString(2, options.repo);
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".review_comments " +
"SELECT src.* " +
"FROM (" + runsQuery + ") r " +
"CROSS JOIN unnest(review_comments(?, ?, r.pull_number)) src " +
"LEFT JOIN " + destSchema + ".review_comments dst ON dst.id = src.id " +
"WHERE dst.id IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(4, options.owner);
insertStatement.setString(5, options.repo);
long previousId = 0;
while (true) {
insertStatement.setLong(3, previousId);
log.info(format("Fetching comments for reviews with id greater than %d", previousId));
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
idStatement.setLong(3, previousId);
log.info("Checking for next reviews without comments");
ResultSet resultSet = idStatement.executeQuery();
if (!resultSet.next()) {
break;
}
previousId = resultSet.getLong(1);
if (resultSet.wasNull()) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncSince(Options options, String name)
throws SQLException
{
return syncSince(options, name, "updated_at");
}
private static boolean syncSince(Options options, String name, String columnName)
throws SQLException
{
Connection conn = options.conn;
String destSchema = options.destSchema;
PreparedStatement lastUpdatedStatement = conn.prepareStatement(
"SELECT COALESCE(MAX(" + columnName + "), TIMESTAMP '1970-01-01') AS latest FROM " + destSchema + "." + name + " WHERE owner = ? AND repo = ?");
lastUpdatedStatement.setString(1, options.owner);
lastUpdatedStatement.setString(2, options.repo);
ResultSet result = lastUpdatedStatement.executeQuery();
result.next();
String lastUpdated = result.getString(1);
PreparedStatement statement = conn.prepareStatement(
"INSERT INTO " + destSchema + "." + name + " " +
"SELECT * FROM unnest(" + name + "(?, ?, ?, CAST(? AS TIMESTAMP))) src");
statement.setString(1, options.owner);
statement.setString(2, options.repo);
statement.setString(4, lastUpdated);
int page = 1;
while (true) {
log.info(format("Fetching %s page number %d", name, page));
long startTime = System.currentTimeMillis();
statement.setInt(3, page++);
int rows = retryExecute(statement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
if (rows == 0) {
break;
}
}
return true;
}
private static boolean syncPulls(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".pulls AS SELECT * FROM " + srcSchema + ".pulls WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON pulls(owner, repo);
// CREATE INDEX ON pulls(id);
// CREATE INDEX ON pulls(user_id);
// CREATE INDEX ON pulls(milestone_id);
// CREATE INDEX ON pulls(assignee_id);
// CREATE INDEX ON pulls(state);
// note that the first one is NOT a primary key, so updated records can be inserted
// and then removed as duplicates by running this in the target database (not supported in Trino):
// DELETE FROM pulls a USING pulls b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// or use the unique_pulls view (from `trino-rest-github/sql/views.sql`) that ignores duplicates
// there's no "since" filter, but we can sort by updated_at, so keep inserting records where this is greater than max
PreparedStatement lastUpdatedStatement = conn.prepareStatement(
"SELECT COALESCE(MAX(updated_at), TIMESTAMP '0000-01-01') AS latest FROM " + destSchema + ".pulls WHERE owner = ? AND repo = ?");
lastUpdatedStatement.setString(1, options.owner);
lastUpdatedStatement.setString(2, options.repo);
ResultSet result = lastUpdatedStatement.executeQuery();
result.next();
String lastUpdated = result.getString(1);
PreparedStatement statement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".pulls " +
"SELECT * FROM unnest(pulls(?, ?, ?)) WHERE updated_at > CAST(? AS TIMESTAMP)");
statement.setString(1, options.owner);
statement.setString(2, options.repo);
statement.setString(4, lastUpdated);
int page = 1;
while (true) {
log.info(format("Fetching pulls page number %d", page));
long startTime = System.currentTimeMillis();
statement.setInt(3, page++);
int rows = retryExecute(statement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
if (rows == 0) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncPullCommits(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".pull_commits AS SELECT * FROM " + srcSchema + ".pull_commits WITH NO DATA");
// consider adding some indexes:
// ALTER TABLE pull_commits ADD PRIMARY KEY (owner, repo, pull_number, sha);
// only fetch pull commits from up to 30 new or updated commits without any in the last update period, if it was updated less than 3 days ago
String runsQuery = format(
"WITH pulls AS (" +
" SELECT number, lag(updated_at, 1, timestamp '1970-01-01 00:00:00') over (partition by number order by updated_at) AS prev_updated_at, updated_at" +
" FROM " + destSchema + ".pulls" +
" WHERE owner = ? AND repo = ? AND number > ?" +
"), " +
"latest AS (" +
" SELECT number, max_by(prev_updated_at, updated_at) AS prev_updated_at, max(updated_at) AS updated_at " +
" FROM pulls" +
" GROUP BY number" +
") " +
"SELECT p.number " +
"FROM latest p " +
"LEFT JOIN " + destSchema + ".pull_commits c ON c.pull_number = p.number " +
"GROUP BY p.number, p.prev_updated_at, p.updated_at " +
"HAVING COUNT(c.sha) = 0 OR (MAX(c.committer_date) < p.prev_updated_at AND p.updated_at > CURRENT_DATE - INTERVAL '3' DAY) " +
"ORDER BY p.number ASC LIMIT %d", 30);
// since there's no difference between pulls without commits and those we have not checked or yet,
// we need to know the last checked pull number and add a condition to fetch lesser numbers
PreparedStatement idStatement = conn.prepareStatement("SELECT max(p.number) FROM (" + runsQuery + ") p");
idStatement.setString(1, options.owner);
idStatement.setString(2, options.repo);
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".pull_commits " +
"SELECT src.* " +
"FROM (" + runsQuery + ") p " +
"CROSS JOIN unnest(pull_commits(?, ?, p.number)) src " +
"LEFT JOIN " + destSchema + ".pull_commits dst ON (dst.pull_number, dst.sha) = (src.pull_number, src.sha) " +
"WHERE dst.sha IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(4, options.owner);
insertStatement.setString(5, options.repo);
long previousId = 0;
while (true) {
insertStatement.setLong(3, previousId);
log.info(format("Fetching commits for pulls with number greater than %d", previousId));
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
idStatement.setLong(3, previousId);
log.info("Checking for next pulls without commits");
ResultSet resultSet = idStatement.executeQuery();
if (!resultSet.next()) {
break;
}
previousId = resultSet.getLong(1);
if (resultSet.wasNull()) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncPullStats(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".pull_stats AS SELECT * FROM " + srcSchema + ".pull_stats WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON pull_stats(owner, repo, pull_number);
// note that the first one is NOT a primary key, so updated records can be inserted
// and then removed as duplicates by running this in the target database (not supported in Trino):
// DELETE FROM pulls a USING pull_stats b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// or use the unique_pull_stats view (from `trino-rest-github/sql/views.sql`) that ignores duplicates
// only fetch pull stats from up to 100 pulls without any in the last update period
String runsQuery = format(
"WITH latest AS (" +
" SELECT owner, repo, number, max(updated_at) AS updated_at " +
" FROM " + destSchema + ".pulls" +
" WHERE owner = ? AND repo = ?" +
" GROUP BY owner, repo, number" +
") " +
"SELECT p.number " +
"FROM latest p " +
"LEFT JOIN " + destSchema + ".pull_stats s ON (s.owner, s.repo, s.pull_number, s.updated_at) = (p.owner, p.repo, p.number, p.updated_at) " +
"WHERE s.pull_number IS NULL " +
"ORDER BY p.number ASC LIMIT %d", 100);
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".pull_stats " +
"SELECT src.* " +
"FROM (SELECT pull_stats(?, ?, p.number).* FROM (" + runsQuery + ") p) src " +
"LEFT JOIN " + destSchema + ".pull_stats dst ON (dst.owner, dst.repo, dst.pull_number, dst.updated_at) = (src.owner, src.repo, src.pull_number, src.updated_at) " +
"WHERE dst.pull_number IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(3, options.owner);
insertStatement.setString(4, options.repo);
while (true) {
log.info("Fetching stats for pulls without any");
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
if (rows == 0) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncReviews(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".reviews AS SELECT * FROM " + srcSchema + ".reviews WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON reviews(owner, repo);
// CREATE INDEX ON reviews(id);
// CREATE INDEX ON reviews(user_id);
// CREATE INDEX ON reviews(pull_number);
// CREATE INDEX ON reviews(state);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using:
// DELETE FROM reviews a USING reviews b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// would be better to just get new reviews but there's no endpoint to get them for the whole repo
// so assuming that review comments might have been fetched first, fetch missing reviews
// check if there are any review comments at all, and if not, call instead syncAllReviews()
ResultSet comments = conn.prepareStatement("SELECT * FROM " + destSchema + ".review_comments LIMIT 1")
.executeQuery();
if (!comments.next()) {
return syncAllReviews(options);
}
// only fetch up to 10 pulls for comments without reviews
String prQuery = format(
"SELECT p.number " +
"FROM " + destSchema + ".unique_review_comments c " +
"LEFT JOIN " + destSchema + ".reviews r ON r.id = c.pull_request_review_id " +
"JOIN " + destSchema + ".unique_pulls p ON p.url = c.pull_request_url " +
"WHERE c.owner = ? AND c.repo = ? AND r.id IS NULL " +
"GROUP BY p.number " +
"ORDER BY p.number ASC LIMIT %d", 10);
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".reviews " +
"SELECT src.* " +
"FROM (" + prQuery + ") p " +
"CROSS JOIN unnest(reviews(?, ?, p.number)) src " +
"LEFT JOIN " + destSchema + ".reviews dst ON dst.id = src.id " +
"WHERE dst.id IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(3, options.owner);
insertStatement.setString(4, options.repo);
while (true) {
log.info("Checking for next review comments without reviews");
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
if (rows == 0) {
break;
}
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncAllReviews(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".reviews AS SELECT * FROM " + srcSchema + ".reviews WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON reviews(owner, repo);
// CREATE INDEX ON reviews(id);
// CREATE INDEX ON reviews(user_id);
// CREATE INDEX ON reviews(pull_number);
// CREATE INDEX ON reviews(state);
// note that the first one is NOT a primary key, so updated records can be inserted and then removed as duplicates using:
// DELETE FROM reviews a USING reviews b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// TODO only fall back to this if there are no reviews at all
// only fetch reviews from up to 30 pulls without any reviews
String runsQuery = format(
"SELECT p.number " +
"FROM " + destSchema + ".unique_pulls p " +
"LEFT JOIN " + destSchema + ".reviews r ON r.pull_number = p.number " +
"WHERE p.owner = ? AND p.repo = ? AND p.number < ? " +
"GROUP BY p.number " +
"HAVING COUNT(r.id) = 0 " +
"ORDER BY p.number DESC LIMIT %d", 30);
// since there's no difference between pulls without reviews and those we have not checked or yet,
// we need to know the last checked pull number and add a condition to fetch lesser numbers
PreparedStatement idStatement = conn.prepareStatement("SELECT min(p.number) FROM (" + runsQuery + ") p");
idStatement.setString(1, options.owner);
idStatement.setString(2, options.repo);
// TODO this only gets missing reviews - doesn't allow to fetch updated reviews
PreparedStatement insertStatement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".reviews " +
"SELECT src.* " +
"FROM (" + runsQuery + ") p " +
"CROSS JOIN unnest(reviews(?, ?, p.number)) src " +
"LEFT JOIN " + destSchema + ".reviews dst ON dst.id = src.id " +
"WHERE dst.id IS NULL");
insertStatement.setString(1, options.owner);
insertStatement.setString(2, options.repo);
insertStatement.setString(4, options.owner);
insertStatement.setString(5, options.repo);
long previousId = Long.MAX_VALUE;
while (true) {
idStatement.setLong(3, previousId);
insertStatement.setLong(3, previousId);
log.info("Checking for next pulls without reviews");
ResultSet resultSet = idStatement.executeQuery();
if (!resultSet.next()) {
break;
}
previousId = resultSet.getLong(1);
if (resultSet.wasNull()) {
break;
}
log.info(format("Fetching reviews for pulls with number less than %d", previousId));
long startTime = System.currentTimeMillis();
int rows = retryExecute(insertStatement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
}
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncWorkflows(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {
conn.createStatement().executeUpdate(
"CREATE TABLE IF NOT EXISTS " + destSchema + ".workflows AS SELECT * FROM " + srcSchema + ".workflows WITH NO DATA");
// consider adding some indexes:
// CREATE INDEX ON workflows(owner, repo);
// CREATE INDEX ON workflows(id);
// note that the first one is NOT a primary key, so updated records can be inserted
// and then removed as duplicates by running this in the target database (not supported in Trino):
// DELETE FROM workflows a USING workflows b WHERE a.updated_at < b.updated_at AND a.id = b.id;
// or use the unique_workflows view (from `trino-rest-github/sql/views.sql`) that ignores duplicates
// there's no "since" filter, but we can sort by updated_at, so keep inserting records where this is greater than max
PreparedStatement lastUpdatedStatement = conn.prepareStatement(
"SELECT COALESCE(MAX(updated_at), TIMESTAMP '0000-01-01') AS latest FROM " + destSchema + ".workflows WHERE owner = ? AND repo = ?");
lastUpdatedStatement.setString(1, options.owner);
lastUpdatedStatement.setString(2, options.repo);
ResultSet result = lastUpdatedStatement.executeQuery();
result.next();
String lastUpdated = result.getString(1);
PreparedStatement statement = conn.prepareStatement(
"INSERT INTO " + destSchema + ".workflows " +
"SELECT * FROM " + srcSchema + ".workflows WHERE owner = ? AND repo = ? AND updated_at > CAST(? AS TIMESTAMP)");
statement.setString(1, options.owner);
statement.setString(2, options.repo);
statement.setString(3, lastUpdated);
log.info("Fetching workflows");
long startTime = System.currentTimeMillis();
int rows = retryExecute(statement);
log.info(format("Inserted %d rows, took %s", rows, Duration.ofMillis(System.currentTimeMillis() - startTime)));
}
catch (Exception e) {
log.severe(e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
private static boolean syncRuns(Options options)
{
Connection conn = options.conn;
String destSchema = options.destSchema;
String srcSchema = options.srcSchema;
try {