-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathsql-lint.ts
More file actions
57 lines (50 loc) · 1.56 KB
/
sql-lint.ts
File metadata and controls
57 lines (50 loc) · 1.56 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
import type { Sql } from "postgres";
import type { StudioBFFSqlLintResult } from "../../data/bff";
import {
createLintDiagnosticsFromPostgresError,
validateSqlForLint,
} from "../../data/postgres-core/sql-lint";
const SQL_LINT_STATEMENT_TIMEOUT = "1000ms";
const SQL_LINT_LOCK_TIMEOUT = "100ms";
const SQL_LINT_IDLE_IN_TRANSACTION_TIMEOUT = "1000ms";
export async function lintPostgresSql(args: {
postgresClient: Sql;
schemaVersion?: string;
sql: string;
}): Promise<StudioBFFSqlLintResult> {
const { postgresClient, schemaVersion, sql } = args;
const validation = validateSqlForLint(sql);
if (!validation.ok) {
return {
diagnostics: [validation.diagnostic],
schemaVersion,
};
}
const diagnostics: StudioBFFSqlLintResult["diagnostics"] = [];
for (const statement of validation.statements) {
try {
await postgresClient.begin(async (tx) => {
await tx.unsafe(
`set local statement_timeout = '${SQL_LINT_STATEMENT_TIMEOUT}'`,
);
await tx.unsafe(`set local lock_timeout = '${SQL_LINT_LOCK_TIMEOUT}'`);
await tx.unsafe(
`set local idle_in_transaction_session_timeout = '${SQL_LINT_IDLE_IN_TRANSACTION_TIMEOUT}'`,
);
await tx.unsafe(`EXPLAIN (FORMAT JSON) ${statement.statement}`);
});
} catch (error: unknown) {
diagnostics.push(
...createLintDiagnosticsFromPostgresError({
error,
positionOffset: statement.from,
sql: statement.statement,
}),
);
}
}
return {
diagnostics,
schemaVersion,
};
}