-
Notifications
You must be signed in to change notification settings - Fork 457
Expand file tree
/
Copy pathreport_server.py
More file actions
4698 lines (3866 loc) · 176 KB
/
report_server.py
File metadata and controls
4698 lines (3866 loc) · 176 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
# -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# -------------------------------------------------------------------------
"""
Handle Thrift requests.
"""
import base64
import html
import json
import os
import re
import shlex
import stat
import time
import zlib
from copy import deepcopy
from collections import OrderedDict, defaultdict, namedtuple
from datetime import datetime, timedelta
from typing import Any, Collection, Dict, List, Optional, Set, Tuple
import sqlalchemy
from sqlalchemy.sql.expression import or_, and_, not_, func, \
asc, desc, union_all, select, bindparam, literal_column, cast, true
from sqlalchemy.orm import contains_eager
from sqlalchemy.types import ARRAY, String
import codechecker_api_shared
from codechecker_api.codeCheckerDBAccess_v6 import constants, ttypes
from codechecker_api.codeCheckerDBAccess_v6.ttypes import \
AnalysisInfoFilter, AnalysisInfoChecker as API_AnalysisInfoChecker, \
BlameData, BlameInfo, BugPathPos, \
CheckerCount, CheckerStatusVerificationDetail, Commit, CommitAuthor, \
CommentData, \
DetectionStatus, DiffType, \
Encoding, ExportData, \
Order, \
ReportData, ReportDetails, ReportStatus, ReviewData, ReviewStatusRule, \
ReviewStatusRuleFilter, ReviewStatusRuleSortMode, \
ReviewStatusRuleSortType, Rule, RunData, RunFilter, RunHistoryData, \
RunReportCount, RunSortType, RunTagCount, \
ReviewStatus as API_ReviewStatus, \
SourceComponentData, SourceFileData, SortMode, SortType, \
SubmittedRunOptions
from codechecker_api_shared.ttypes import ErrorCode, RequestFailed
from codechecker_common import util
from codechecker_common.util import thrift_to_json
from codechecker_common.logger import get_logger
from codechecker_web.shared import webserver_context
from codechecker_web.shared import convert
from codechecker_server.profiler import timeit
from .. import permissions
from ..database import db_cleanup
from ..database.config_db_model import Product
from ..database.database import conv, DBSession, escape_like
from ..database.run_db_model import \
AnalysisInfo, \
AnalysisInfoChecker as DB_AnalysisInfoChecker, AnalysisInfoFile, \
AnalyzerStatistic, \
BugPathEvent, BugReportPoint, \
CleanupPlan, CleanupPlanReportHash, Checker, Comment, \
ExtendedReportData, \
File, FileContent, \
Report, ReportAnnotations, ReportAnalysisInfo, ReviewStatus, \
Run, RunHistory, RunHistoryAnalysisInfo, RunLock, \
SourceComponent, SourceComponentFile, FilterPreset
from .common import exc_to_thrift_reqfail
from .thrift_enum_helper import detection_status_enum, \
detection_status_str, report_status_enum, \
review_status_enum, review_status_str, report_extended_data_type_enum
from .report_annotations import report_annotation_types
# These names are inherited from Thrift stubs.
# pylint: disable=invalid-name
LOG = get_logger('server')
GEN_OTHER_COMPONENT_NAME = "Other (auto-generated)"
SQLITE_MAX_VARIABLE_NUMBER = 999
SQLITE_MAX_COMPOUND_SELECT = 500
class CommentKindValue:
USER = 0
SYSTEM = 1
def comment_kind_from_thrift_type(kind):
""" Convert the given comment kind from Thrift type to Python enum. """
if kind == ttypes.CommentKind.USER:
return CommentKindValue.USER
elif kind == ttypes.CommentKind.SYSTEM:
return CommentKindValue.SYSTEM
assert False, f"Unknown ttypes.CommentKind: {kind}"
def comment_kind_to_thrift_type(kind):
""" Convert the given comment kind from Python enum to Thrift type. """
if kind == CommentKindValue.USER:
return ttypes.CommentKind.USER
elif kind == CommentKindValue.SYSTEM:
return ttypes.CommentKind.SYSTEM
assert False, f"Unknown CommentKindValue: {kind}"
def verify_limit_range(limit):
"""Verify limit value for the queries.
Query limit should not be larger than the max allowed value.
Max is returned if the value is larger than max.
"""
max_query_limit = constants.MAX_QUERY_SIZE
if not limit:
return max_query_limit
if limit > max_query_limit:
LOG.warning('Query limit %d was larger than max query limit %d, '
'setting limit to %d',
limit,
max_query_limit,
max_query_limit)
limit = max_query_limit
return limit
def slugify(text):
"""
Removes and replaces special characters in a given text.
"""
# Removes non-alpha characters.
norm_text = re.sub(r'[^\w\s\-/]', '', text)
# Converts spaces and slashes to underscores.
norm_text = re.sub(r'([\s]+|[/]+)', '_', norm_text)
return norm_text
def get_component_values(
component: SourceComponent
) -> Tuple[List[str], List[str]]:
"""
Returns a tuple where the first item contains a list paths that should be
included and the second item contains a list of paths that should be
skipped.
E.g.:
+/a/b/x.cpp
+/a/b/y.cpp
-/a/b
On the above component value this function will return the following:
(['/a/b/x.cpp', '/a/b/y.cpp'], ['/a/b'])
"""
include = []
skip = []
values = component.value.decode('utf-8').split('\n')
for value in values:
value = value.strip()
if not value:
continue
v = value[1:]
if value[0] == '+':
include.append(v)
elif value[0] == '-':
skip.append(v)
return include, skip
def update_source_component_files(
session: DBSession,
component: Optional[SourceComponent] = None
):
"""
Refreshes the SourceComponentFile table for a specific source component.
If `component` is None, then all source components are updated.
"""
if component is None:
all_components = session.query(SourceComponent)
else:
all_components = [component]
# 1. Delete existing associations for this component
session.query(SourceComponentFile) \
.filter(SourceComponentFile.source_component_name.in_(
map(lambda component: component.name, all_components))) \
.delete(synchronize_session=False)
for comp in all_components:
# 2. Re-calculate associations
include, skip = get_component_values(comp)
file_ids_query = None
if skip and include:
include_q, skip_q = get_include_skip_queries(include, skip)
file_ids_query = include_q.except_(skip_q)
elif include:
include_q, _ = get_include_skip_queries(include, [])
file_ids_query = include_q
elif skip:
_, skip_q = get_include_skip_queries([], skip)
file_ids_query = select(File.id).where(File.id.notin_(skip_q))
if file_ids_query is not None:
file_ids = session.execute(file_ids_query).fetchall()
if file_ids:
session.bulk_insert_mappings(
SourceComponentFile,
[{'source_component_name': comp.name,
'file_id': fid[0]} for fid in file_ids])
def process_report_filter(
session,
run_ids,
report_filter,
cmp_data=None,
keep_all_annotations=False
):
"""
Process the new report filter.
"""
AND = []
cmp_filter_expr, join_tables = process_cmp_data_filter(
session, run_ids, report_filter, cmp_data)
if cmp_filter_expr is not None:
AND.append(cmp_filter_expr)
if report_filter is None:
return and_(*AND), join_tables
if report_filter.reportHash == []:
return and_(False), []
if report_filter.filepath:
if report_filter.fileMatchesAnyPoint:
AND.append(Report.id.in_(get_reports_by_files(
session,
report_filter.filepath)))
else:
OR = [File.filepath.ilike(conv(fp))
for fp in report_filter.filepath]
if OR:
AND.append(or_(*OR))
join_tables.append(File)
if report_filter.checkerMsg:
OR = [Report.checker_message.ilike(conv(cm))
for cm in report_filter.checkerMsg]
if OR:
AND.append(or_(*OR))
if report_filter.analyzerNames or report_filter.checkerName \
or report_filter.severity:
if report_filter.analyzerNames:
OR = [Checker.analyzer_name.ilike(conv(an))
for an in report_filter.analyzerNames]
if OR:
AND.append(or_(*OR))
if report_filter.checkerName:
OR = [Checker.checker_name.ilike(conv(cn))
for cn in report_filter.checkerName]
if OR:
AND.append(or_(*OR))
if report_filter.severity:
AND.append(Checker.severity.in_(report_filter.severity))
join_tables.append(Checker)
if report_filter.runName:
OR = [Run.name.ilike(conv(rn))
for rn in report_filter.runName]
if OR:
AND.append(or_(*OR))
join_tables.append(Run)
if report_filter.reportHash:
OR = []
no_joker = []
for rh in report_filter.reportHash:
if '*' in rh:
OR.append(Report.bug_id.ilike(conv(rh)))
else:
no_joker.append(rh)
if no_joker:
OR.append(Report.bug_id.in_(no_joker))
if OR:
AND.append(or_(*OR))
if report_filter.cleanupPlanNames:
OR = []
for cleanup_plan_name in report_filter.cleanupPlanNames:
q = select(CleanupPlanReportHash.bug_hash) \
.where(
CleanupPlanReportHash.cleanup_plan_id.in_(
select(CleanupPlan.id)
.where(CleanupPlan.name == cleanup_plan_name)
.distinct()
)) \
.distinct()
OR.append(Report.bug_id.in_(q))
if OR:
AND.append(or_(*OR))
if report_filter.reportStatus:
dst = list(map(detection_status_str,
(DetectionStatus.NEW,
DetectionStatus.UNRESOLVED,
DetectionStatus.REOPENED)))
rst = list(map(review_status_str,
(API_ReviewStatus.UNREVIEWED,
API_ReviewStatus.CONFIRMED)))
OR = []
filter_query = and_(
Report.review_status.in_(rst),
Report.detection_status.in_(dst)
)
if ReportStatus.OUTSTANDING in report_filter.reportStatus:
OR.append(filter_query)
if ReportStatus.CLOSED in report_filter.reportStatus:
OR.append(not_(filter_query))
if OR:
AND.append(or_(*OR))
if report_filter.detectionStatus:
dst = list(map(detection_status_str,
report_filter.detectionStatus))
AND.append(Report.detection_status.in_(dst))
if report_filter.reviewStatus:
OR = [Report.review_status.in_(
list(map(review_status_str, report_filter.reviewStatus)))]
if OR:
AND.append(or_(*OR))
if report_filter.firstDetectionDate is not None:
date = datetime.fromtimestamp(report_filter.firstDetectionDate)
AND.append(Report.detected_at >= date)
if report_filter.fixDate is not None:
date = datetime.fromtimestamp(report_filter.fixDate)
AND.append(Report.detected_at < date)
if report_filter.date:
detected_at = report_filter.date.detected
if detected_at:
if detected_at.before:
detected_before = datetime.fromtimestamp(detected_at.before)
AND.append(Report.detected_at <= detected_before)
if detected_at.after:
detected_after = datetime.fromtimestamp(detected_at.after)
AND.append(Report.detected_at >= detected_after)
fixed_at = report_filter.date.fixed
if fixed_at:
if fixed_at.before:
fixed_before = datetime.fromtimestamp(fixed_at.before)
AND.append(Report.fixed_at <= fixed_before)
if fixed_at.after:
fixed_after = datetime.fromtimestamp(fixed_at.after)
AND.append(Report.fixed_at >= fixed_after)
if report_filter.runHistoryTag:
OR = []
for history_date in report_filter.runHistoryTag:
date = datetime.strptime(history_date,
'%Y-%m-%d %H:%M:%S.%f')
OR.append(and_(Report.detected_at <= date, or_(
Report.fixed_at.is_(None), Report.fixed_at >= date)))
if OR:
AND.append(or_(*OR))
if report_filter.componentNames:
if report_filter.componentMatchesAnyPoint:
AND.append(Report.id.in_(get_reports_by_components(
session,
report_filter.componentNames,
False)))
elif report_filter.fullReportPathInComponent:
AND.append(Report.id.in_(get_reports_by_components(
session,
report_filter.componentNames,
True)))
else:
AND.append(process_source_component_filter(
session, report_filter.componentNames))
join_tables.append(File)
if report_filter.bugPathLength is not None:
min_path_length = report_filter.bugPathLength.min
if min_path_length is not None:
AND.append(Report.path_length >= min_path_length)
max_path_length = report_filter.bugPathLength.max
if max_path_length is not None:
AND.append(Report.path_length <= max_path_length)
if report_filter.annotations is not None:
annotations = defaultdict(list)
for annotation in report_filter.annotations:
annotations[annotation.first].append(annotation.second)
OR = []
for key, values in annotations.items():
if keep_all_annotations:
OR.append(or_(
ReportAnnotations.key != key,
*[ReportAnnotations.value.ilike(conv(v))
for v in values]))
else:
OR.append(and_(
ReportAnnotations.key == key,
or_(*[ReportAnnotations.value.ilike(conv(v))
for v in values])) if values else and_(
ReportAnnotations.key == key))
if OR:
AND.append(or_(*OR))
filter_expr = and_(*AND) if AND else true()
return filter_expr, join_tables
def process_source_component_filter(session, component_names):
""" Process source component filter.
The virtual auto-generated Other component will be handled separately and
the query part will be added to the filter.
"""
OR = []
for component_name in component_names:
if component_name == GEN_OTHER_COMPONENT_NAME:
file_query = get_other_source_component_file_query(session)
else:
file_query = get_source_component_file_query(session,
component_name)
if file_query is not None:
OR.append(file_query)
return or_(*OR) if OR else true()
def filter_open_reports_in_tags(results, run_ids, tag_ids):
"""
Adding filters on "results" query which filter on open reports in
given runs and tags.
For further information see the documentation of
filter_open_reports_in_tags_old().
"""
if run_ids:
results = results.filter(Report.run_id.in_(run_ids))
if tag_ids:
results = results.outerjoin(
RunHistory, RunHistory.run_id == Report.run_id) \
.filter(RunHistory.id.in_(tag_ids)) \
.filter(get_open_reports_date_filter_query())
return results
def filter_open_reports_in_tags_old(results, run_ids, tag_ids):
"""
Adding filters on "results" query which filter on open reports in
given runs and tags.
This function is almost the same as filter_open_reports_in_tags() except
that is uses get_open_reports_date_filter_query_old() for filtering open
reports on a given date. This function is duplicated, because we didn't
want to add an extra parameter for this function, but express the fact that
an old client (i.e. API version before 6.50) should be given a different
result set.
This function and its duplicate are used in getDiffResultHash() which
should behave differently when called by an old client. The reasons of this
different behavior is described a previous commit
(f6d0fedaf14b583df7bd26078a8a22b557be57c6) where another case of the issue
was fixed.
"""
if run_ids:
results = results.filter(Report.run_id.in_(run_ids))
if tag_ids:
results = results.outerjoin(
RunHistory, RunHistory.run_id == Report.run_id) \
.filter(RunHistory.id.in_(tag_ids)) \
.filter(get_open_reports_date_filter_query_old())
return results
def get_include_skip_queries(
include: List[str],
skip: List[str]
):
""" Get queries for include and skip values of a component.
To get the include and skip lists use the 'get_component_values' function.
"""
include_q = select(File.id) \
.where(or_(*[
File.filepath.like(conv(fp)) for fp in include])) \
.distinct()
skip_q = select(File.id) \
.where(or_(*[
File.filepath.like(conv(fp)) for fp in skip])) \
.distinct()
return include_q, skip_q
def get_source_component_file_query(
session: DBSession,
component_name: str
):
""" Get filter query for a single source component. """
return File.id.in_(
session.query(SourceComponentFile.file_id)
.filter(SourceComponentFile.source_component_name == component_name)
)
def get_reports_by_bugpath_filter_for_single_origin(
session,
file_filter_q
) -> Set[int]:
"""
This function returns a query for report IDs that are fully contained
within the files specified by the file_filter_q query."""
LOG.info("get_reports_by_bugpath_filter file_filter_q: %s", file_filter_q)
q_report = session.query(Report.id) \
.join(File, File.id == Report.file_id) \
.filter(file_filter_q)
q_bugpathevent = session.query(BugPathEvent.report_id) \
.join(File, File.id == BugPathEvent.file_id) \
.filter(file_filter_q)
q_bugreportpoint = session.query(BugReportPoint.report_id) \
.join(File, File.id == BugReportPoint.file_id) \
.filter(file_filter_q)
q_extendedreportdata = session.query(ExtendedReportData.report_id) \
.join(File, File.id == ExtendedReportData.file_id) \
.filter(file_filter_q)
neg_q_report = session.query(Report.id) \
.join(File, File.id != Report.file_id) \
.filter(file_filter_q)
neg_q_bugpathevent = session.query(BugPathEvent.report_id) \
.join(File, File.id != BugPathEvent.file_id) \
.filter(file_filter_q)
neg_q_bugreportpoint = session.query(BugReportPoint.report_id) \
.join(File, File.id != BugReportPoint.file_id) \
.filter(file_filter_q)
neg_q_extendedreportdata = session.query(ExtendedReportData.report_id) \
.join(File, File.id != ExtendedReportData.file_id) \
.filter(file_filter_q)
return q_report.union(
q_bugpathevent,
q_bugreportpoint,
q_extendedreportdata).except_(
neg_q_report,
neg_q_bugpathevent,
neg_q_bugreportpoint,
neg_q_extendedreportdata)
def get_reports_by_bugpath_filter(session, file_filter_q) -> Set[int]:
"""
This function returns a query for report IDs that are related to any file
described by the query in the second parameter, either because their bug
path goes through these files, or there is any bug note, etc. in these
files.
"""
q_report = session.query(Report.id) \
.join(File, File.id == Report.file_id) \
.filter(file_filter_q)
q_bugpathevent = session.query(BugPathEvent.report_id) \
.join(File, File.id == BugPathEvent.file_id) \
.filter(file_filter_q)
q_bugreportpoint = session.query(BugReportPoint.report_id) \
.join(File, File.id == BugReportPoint.file_id) \
.filter(file_filter_q)
q_extendedreportdata = session.query(ExtendedReportData.report_id) \
.join(File, File.id == ExtendedReportData.file_id) \
.filter(file_filter_q)
return q_report.union(
q_bugpathevent,
q_extendedreportdata,
q_bugreportpoint)
def get_reports_by_components(session,
component_names: List[str],
single_origin: bool) -> Set[int]:
"""
This function returns a set of report IDs that are related to any component
in the second parameter, either because their bug path goes through these
components, or there is any bug note, etc. in these components.
"""
source_component_filter = \
process_source_component_filter(session, component_names)
if single_origin:
return get_reports_by_bugpath_filter_for_single_origin(
session, source_component_filter)
return get_reports_by_bugpath_filter(session, source_component_filter)
def get_reports_by_files(session, files: List[str]) -> Set[int]:
"""
This function returns a set of report IDs that are related to any file in
the second parameter, either because their bug path goes through these
files, or there is any bug note, etc. in these files.
"""
file_filter = or_(*[File.filepath.ilike(conv(fp)) for fp in files])
return get_reports_by_bugpath_filter(session, file_filter)
def get_other_source_component_file_query(session):
""" Get filter query for the auto-generated Others component.
If there are no user defined source components in the database this
function will return with None.
The returned query will look like this:
(Files NOT IN Component_1) AND (Files NOT IN Component_2) ... AND
(Files NOT IN Component_N)
"""
# Check if there are any source components
if not session.query(SourceComponent).count():
return None
files_in_components = session.query(SourceComponentFile.file_id)
return File.id.notin_(files_in_components)
def get_open_reports_date_filter_query(tbl=Report, date=RunHistory.time):
""" Get open reports date filter. """
return and_(tbl.detected_at <= date,
or_(tbl.fixed_at.is_(None),
tbl.fixed_at > date))
def get_open_reports_date_filter_query_old(tbl=Report, date=RunHistory.time):
""" Get open reports date filter.
This function is a dupliation of get_open_reports_date_filter_query().
For the reson of duplication see the documentation of
filter_open_reports_in_tags_old().
"""
return tbl.detected_at <= date
def get_diff_bug_id_query(session, run_ids, tag_ids, open_reports_date):
""" Get bug id query for diff. """
q = session.query(Report.bug_id.distinct())
if run_ids:
q = q.filter(Report.run_id.in_(run_ids))
if not tag_ids and not open_reports_date:
q = q.filter(Report.fixed_at.is_(None))
if tag_ids:
q = q.outerjoin(RunHistory,
RunHistory.run_id == Report.run_id) \
.filter(RunHistory.id.in_(tag_ids)) \
.filter(get_open_reports_date_filter_query())
if open_reports_date:
date = datetime.fromtimestamp(open_reports_date)
q = q.filter(get_open_reports_date_filter_query(Report, date))
return q
def get_diff_bug_id_filter(run_ids, tag_ids, open_reports_date):
""" Get bug id filter for diff. """
AND = []
if run_ids:
AND.append(Report.run_id.in_(run_ids))
if tag_ids:
AND.append(RunHistory.id.in_(tag_ids))
AND.append(get_open_reports_date_filter_query())
if open_reports_date:
date = datetime.fromtimestamp(open_reports_date)
AND.append(get_open_reports_date_filter_query(Report, date))
return and_(*AND)
def get_diff_run_id_query(session, run_ids, tag_ids):
""" Get run id query for diff. """
q = session.query(Run.id.distinct())
if run_ids:
q = q.filter(Run.id.in_(run_ids))
if tag_ids:
q = q.outerjoin(RunHistory,
RunHistory.run_id == Run.id) \
.filter(RunHistory.id.in_(tag_ids))
return q
def is_cmp_data_empty(cmp_data):
""" True if the parameter is None or no filter fields are set. """
if not cmp_data:
return True
return not any([cmp_data.runIds,
cmp_data.runTag,
cmp_data.openReportsDate])
def is_baseline_empty(report_filter):
""" True if the parameter is None or no baseline filter fields are set. """
if not report_filter:
return True
return not any([report_filter.runTag,
report_filter.openReportsDate])
def process_cmp_data_filter(session, run_ids, report_filter, cmp_data):
""" Process compare data filter. """
base_tag_ids = report_filter.runTag if report_filter else None
base_open_reports_date = report_filter.openReportsDate \
if report_filter else None
if is_cmp_data_empty(cmp_data):
if not run_ids and is_baseline_empty(report_filter):
return None, []
diff_filter = get_diff_bug_id_filter(
run_ids, base_tag_ids, base_open_reports_date)
join_tables = []
if run_ids:
join_tables.append(Run)
if base_tag_ids:
join_tables.append(RunHistory)
return and_(diff_filter), join_tables
query_base = get_diff_bug_id_query(session, run_ids, base_tag_ids,
base_open_reports_date)
query_base_runs = get_diff_run_id_query(session, run_ids, base_tag_ids)
query_new = get_diff_bug_id_query(session, cmp_data.runIds,
cmp_data.runTag,
cmp_data.openReportsDate)
query_new_runs = get_diff_run_id_query(session, cmp_data.runIds,
cmp_data.runTag)
if cmp_data.diffType == DiffType.NEW:
return and_(Report.bug_id.in_(query_new.except_(query_base)),
Report.run_id.in_(query_new_runs)), [Run]
elif cmp_data.diffType == DiffType.RESOLVED:
return and_(Report.bug_id.in_(query_base.except_(query_new)),
Report.run_id.in_(query_base_runs)), [Run]
elif cmp_data.diffType == DiffType.UNRESOLVED:
return and_(Report.bug_id.in_(query_base.intersect(query_new)),
Report.run_id.in_(query_new_runs)), [Run]
else:
raise codechecker_api_shared.ttypes.RequestFailed(
codechecker_api_shared.ttypes.ErrorCode.DATABASE,
'Unsupported diff type: ' + str(cmp_data.diffType))
def process_run_history_filter(query, run_ids, run_history_filter):
"""
Process run history filter.
"""
if run_ids:
query = query.filter(RunHistory.run_id.in_(run_ids))
if run_history_filter:
if run_history_filter.tagNames:
OR = [RunHistory.version_tag.ilike('{0}'.format(conv(
escape_like(name, '\\'))), escape='\\') for
name in run_history_filter.tagNames]
query = query.filter(or_(*OR))
if run_history_filter.tagIds:
query = query.filter(RunHistory.id.in_(run_history_filter.tagIds))
stored = run_history_filter.stored
if stored:
if stored.before:
stored_before = datetime.fromtimestamp(stored.before)
query = query.filter(RunHistory.time <= stored_before)
if stored.after:
stored_after = datetime.fromtimestamp(stored.after)
query = query.filter(RunHistory.time >= stored_after)
return query
def process_run_filter(session, query, run_filter):
"""
Process run filter.
"""
if run_filter is None:
return query
if run_filter.ids:
query = query.filter(Run.id.in_(run_filter.ids))
if run_filter.names:
if run_filter.exactMatch:
query = query.filter(Run.name.in_(run_filter.names))
else:
OR = [Run.name.ilike('{0}'.format(conv(
escape_like(name, '\\'))), escape='\\') for
name in run_filter.names]
query = query.filter(or_(*OR))
if run_filter.beforeTime:
date = datetime.fromtimestamp(run_filter.beforeTime)
query = query.filter(Run.date < date)
if run_filter.afterTime:
date = datetime.fromtimestamp(run_filter.afterTime)
query = query.filter(Run.date > date)
if run_filter.beforeRun:
run = session.query(Run.date) \
.filter(Run.name == run_filter.beforeRun) \
.one_or_none()
if run:
query = query.filter(Run.date < run.date)
if run_filter.afterRun:
run = session.query(Run.date) \
.filter(Run.name == run_filter.afterRun) \
.one_or_none()
if run:
query = query.filter(Run.date > run.date)
return query
def get_report_details(session, report_ids):
"""
Returns report details for the given report ids.
"""
details = {}
# Get bug path events.
bug_path_events = session.query(BugPathEvent, File.filepath) \
.filter(BugPathEvent.report_id.in_(report_ids)) \
.outerjoin(File,
File.id == BugPathEvent.file_id) \
.order_by(BugPathEvent.report_id, BugPathEvent.order)
bug_events_list = defaultdict(list)
for event, file_path in bug_path_events:
report_id = event.report_id
event = bugpathevent_db_to_api(event)
event.filePath = file_path
bug_events_list[report_id].append(event)
# Get bug report points.
bug_report_points = session.query(BugReportPoint, File.filepath) \
.filter(BugReportPoint.report_id.in_(report_ids)) \
.outerjoin(File,
File.id == BugReportPoint.file_id) \
.order_by(BugReportPoint.report_id, BugReportPoint.order)
bug_point_list = defaultdict(list)
for bug_point, file_path in bug_report_points:
report_id = bug_point.report_id
bug_point = bugreportpoint_db_to_api(bug_point)
bug_point.filePath = file_path
bug_point_list[report_id].append(bug_point)
# Get extended report data.
extended_data_list = defaultdict(list)
q = session.query(ExtendedReportData, File.filepath) \
.filter(ExtendedReportData.report_id.in_(report_ids)) \
.outerjoin(File,
File.id == ExtendedReportData.file_id)
for data, file_path in q:
report_id = data.report_id
extended_data = extended_data_db_to_api(data)
extended_data.filePath = file_path
extended_data_list[report_id].append(extended_data)
# Get Comments for report data
comment_data_list = defaultdict(list)
comment_query = session.query(Comment, Report.id)\
.filter(Report.id.in_(report_ids)) \
.outerjoin(Report, Report.bug_id == Comment.bug_hash) \
.order_by(Comment.created_at.desc())
for data, report_id in comment_query:
comment_data = comment_data_db_to_api(data)
comment_data_list[report_id].append(comment_data)
for report_id in report_ids:
details[report_id] = \
ReportDetails(pathEvents=bug_events_list[report_id],
executionPath=bug_point_list[report_id],
extendedData=extended_data_list[report_id],
comments=comment_data_list[report_id])
return details
def bugpathevent_db_to_api(bpe):
return ttypes.BugPathEvent(
startLine=bpe.line_begin,
startCol=bpe.col_begin,
endLine=bpe.line_end,
endCol=bpe.col_end,
msg=bpe.msg,
fileId=bpe.file_id)
def bugreportpoint_db_to_api(brp):
return BugPathPos(
startLine=brp.line_begin,
startCol=brp.col_begin,
endLine=brp.line_end,
endCol=brp.col_end,
fileId=brp.file_id)
def extended_data_db_to_api(erd):
return ttypes.ExtendedReportData(
type=report_extended_data_type_enum(erd.type),
startLine=erd.line_begin,
startCol=erd.col_begin,
endLine=erd.line_end,
endCol=erd.col_end,
message=erd.message,
fileId=erd.file_id)
def comment_data_db_to_api(comm):
"""
Returns a CommentData Object with all the relevant fields
"""
return ttypes.CommentData(
id=comm.id,
author=comm.author,
message=get_comment_msg(comm),
createdAt=str(comm.created_at),