forked from github/vscode-codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery-runner.ts
More file actions
297 lines (265 loc) · 8.57 KB
/
query-runner.ts
File metadata and controls
297 lines (265 loc) · 8.57 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
import { window, Uri } from "vscode";
import type { CancellationToken, MessageItem } from "vscode";
import type { CodeQLCliServer } from "../codeql-cli/cli";
import type { ProgressCallback } from "../common/vscode/progress";
import { UserCancellationException } from "../common/vscode/progress";
import type { DatabaseItem } from "../databases/local-databases/database-item";
import { QueryOutputDir } from "../local-queries/query-output-dir";
import type {
ClearCacheMode,
ClearCacheParams,
Position,
QueryResultType,
TrimCacheParams,
TrimCacheWithModeParams,
} from "./messages";
import {
clearCache,
clearPackCache,
deregisterDatabases,
registerDatabases,
trimCache,
trimCacheWithMode,
upgradeDatabase,
} from "./messages";
import type { BaseLogger, Logger } from "../common/logging";
import { join } from "path";
import { nanoid } from "nanoid";
import type { QueryServerClient } from "./query-server-client";
import { getOnDiskWorkspaceFolders } from "../common/vscode/workspace-folders";
import { compileAndRunQueryAgainstDatabaseCore } from "./run-queries";
export interface CoreQueryTarget {
/** Path to the query source file. */
queryPath: string;
/**
* Base name to use for output files, without extension. For example, "foo" will result in the
* BQRS file being written to "<outputdir>/foo.bqrs".
*/
outputBaseName: string;
/**
* Optional position of text to be used as QuickEval target. This need not be in the same file as
* `queryPath`.
*/
quickEvalPosition?: Position;
/**
* If this is quick eval, whether to only count the number of results.
*/
quickEvalCountOnly?: boolean;
}
export interface CoreQueryResult {
readonly resultType: QueryResultType;
readonly message: string | undefined;
readonly evaluationTime: number;
/**
* The base name of the output file. Append '.bqrs' and join with the output directory to get the
* path to the BQRS.
*/
readonly outputBaseName: string;
}
export interface CoreQueryResults {
/** A map from query path to its results. */
readonly results: Map<string, CoreQueryResult>;
}
export interface CoreQueryRun {
readonly queryTargets: CoreQueryTarget[];
readonly dbPath: string;
readonly id: string;
readonly outputDir: QueryOutputDir;
evaluate(
progress: ProgressCallback,
token: CancellationToken,
logger: BaseLogger,
): Promise<CoreCompletedQuery>;
}
/** Includes both the results of the query and the initial information from `CoreQueryRun`. */
export type CoreCompletedQuery = CoreQueryResults &
Omit<CoreQueryRun, "evaluate">;
type OnQueryRunStartingListener = (dbPath: Uri) => Promise<void>;
export class QueryRunner {
constructor(public readonly qs: QueryServerClient) {}
// Event handlers that get notified whenever a query is about to start running.
// Can't use vscode EventEmitters since they are not asynchronous.
private readonly onQueryRunStartingListeners: OnQueryRunStartingListener[] =
[];
public onQueryRunStarting(listener: OnQueryRunStartingListener) {
this.onQueryRunStartingListeners.push(listener);
}
private async fireQueryRunStarting(dbPath: Uri) {
await Promise.all(this.onQueryRunStartingListeners.map((l) => l(dbPath)));
}
get cliServer(): CodeQLCliServer {
return this.qs.cliServer;
}
get customLogDirectory(): string | undefined {
return this.qs.config.customLogDirectory;
}
get logger(): Logger {
return this.qs.logger;
}
async restartQueryServer(progress: ProgressCallback): Promise<void> {
await this.qs.restartQueryServer(progress);
}
onStart(callBack: (progress: ProgressCallback) => Promise<void>) {
this.qs.onDidStartQueryServer(callBack);
}
async clearCacheInDatabase(dbItem: DatabaseItem): Promise<void> {
if (dbItem.contents === undefined) {
throw new Error("Can't clear the cache in an invalid database.");
}
const db = dbItem.databaseUri.fsPath;
const params: ClearCacheParams = {
dryRun: false,
db,
};
await this.qs.sendRequest(clearCache, params);
}
async trimCacheInDatabase(dbItem: DatabaseItem): Promise<void> {
if (dbItem.contents === undefined) {
throw new Error("Can't trim the cache in an invalid database.");
}
const db = dbItem.databaseUri.fsPath;
const params: TrimCacheParams = {
db,
};
await this.qs.sendRequest(trimCache, params);
}
async trimCacheWithModeInDatabase(
dbItem: DatabaseItem,
mode: ClearCacheMode,
): Promise<void> {
if (dbItem.contents === undefined) {
throw new Error("Can't clean the cache in an invalid database.");
}
const db = dbItem.databaseUri.fsPath;
const params: TrimCacheWithModeParams = {
db,
mode,
};
await this.qs.sendRequest(trimCacheWithMode, params);
}
public async compileAndRunQueryAgainstDatabaseCore(
dbPath: string,
queries: CoreQueryTarget[],
additionalPacks: string[],
extensionPacks: string[] | undefined,
additionalRunQueryArgs: Record<string, unknown>,
generateEvalLog: boolean,
outputDir: QueryOutputDir,
progress: ProgressCallback,
token: CancellationToken,
templates: Record<string, string> | undefined,
logger: BaseLogger,
): Promise<CoreQueryResults> {
await this.fireQueryRunStarting(Uri.file(dbPath));
return await compileAndRunQueryAgainstDatabaseCore(
this.qs,
dbPath,
queries,
generateEvalLog,
additionalPacks,
extensionPacks,
additionalRunQueryArgs,
outputDir,
progress,
token,
templates,
logger,
);
}
async deregisterDatabase(dbItem: DatabaseItem): Promise<void> {
if (dbItem.contents) {
const databases: string[] = [dbItem.databaseUri.fsPath];
await this.qs.sendRequest(deregisterDatabases, { databases });
}
}
async registerDatabase(dbItem: DatabaseItem): Promise<void> {
if (dbItem.contents) {
const databases: string[] = [dbItem.databaseUri.fsPath];
await this.qs.sendRequest(registerDatabases, { databases });
}
}
async clearPackCache(): Promise<void> {
await this.qs.sendRequest(clearPackCache, {});
}
async upgradeDatabaseExplicit(
dbItem: DatabaseItem,
progress: ProgressCallback,
token: CancellationToken,
): Promise<void> {
const yesItem = { title: "Yes", isCloseAffordance: false };
const noItem = { title: "No", isCloseAffordance: true };
const dialogOptions: MessageItem[] = [yesItem, noItem];
const message = `Should the database ${dbItem.databaseUri.fsPath} be destructively upgraded?\n\nThis should not be necessary to run queries
as we will non-destructively update it anyway.`;
const chosenItem = await window.showInformationMessage(
message,
{ modal: true },
...dialogOptions,
);
if (chosenItem !== yesItem) {
throw new UserCancellationException(
"User cancelled the database upgrade.",
);
}
await this.qs.sendRequest(
upgradeDatabase,
{
db: dbItem.databaseUri.fsPath,
additionalPacks: getOnDiskWorkspaceFolders(),
},
token,
progress,
);
}
/**
* Create a `CoreQueryRun` object. This creates an object whose `evaluate()` function can be
* called to actually evaluate the query. The returned object also contains information about the
* query evaluation that is known even before evaluation starts, including the unique ID of the
* evaluation and the path to its output directory.
*/
public createQueryRun(
dbPath: string,
queries: CoreQueryTarget[],
generateEvalLog: boolean,
additionalPacks: string[],
extensionPacks: string[] | undefined,
additionalRunQueryArgs: Record<string, unknown>,
queryStorageDir: string,
queryBasename: string,
templates: Record<string, string> | undefined,
): CoreQueryRun {
const id = `${queryBasename}-${nanoid()}`;
const outputDir = new QueryOutputDir(join(queryStorageDir, id));
return {
queryTargets: queries,
dbPath,
id,
outputDir,
evaluate: async (
progress: ProgressCallback,
token: CancellationToken,
logger: BaseLogger,
): Promise<CoreCompletedQuery> => {
return {
id,
outputDir,
dbPath,
queryTargets: queries,
...(await this.compileAndRunQueryAgainstDatabaseCore(
dbPath,
queries,
additionalPacks,
extensionPacks,
additionalRunQueryArgs,
generateEvalLog,
outputDir,
progress,
token,
templates,
logger,
)),
};
},
};
}
}