Skip to content

Commit

Permalink
Merge pull request #82 from senkenn:senkenn/issue80
Browse files Browse the repository at this point in the history
Fix format bug for typescript and add related tests
  • Loading branch information
senkenn authored Jun 21, 2024
2 parents 03ced56 + 7357947 commit 228cf4c
Show file tree
Hide file tree
Showing 13 changed files with 166 additions and 10 deletions.
35 changes: 35 additions & 0 deletions vsce-test/out/suite-rs/__snapshots__/extension.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,41 @@ ORDER BY
"
`;
exports[`Formatting Test Should be formatted with diesel function 1`] = `
"use diesel::prelude::*;
use diesel::sql_query;
mod model;
//do change database-url if you don't want your code to break
fn getdbconn() -> PgConnection {
let database_url = "Database-URL";
PgConnection::establish(&database_url).unwrap()
}
fn main() {
let conn = getdbconn();
let results = sql_query(
r#"
SELECT
id,
description,
done
FROM
todos
WHERE
id = ?
ORDER BY
id
"#,
)
.bind::<diesel::sql_types::Integer, _>(1)
.load::<model::User>(&conn)
.unwrap();
println!("{:?}", results);
}
"
`;
exports[`Formatting Test Should be formatted with indent if config is enabled(default: off) 1`] = `
"use sqlx::postgres::PgPool;
use std::env;
Expand Down
25 changes: 25 additions & 0 deletions vsce-test/out/suite-ts/__snapshots__/extension.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,28 @@ main()
});
"
`;
exports[`Formatting Test Should be formatted with user-defined function 1`] = `
"import { getConnection, query } from "./lib/db";
(async () => {
const connection = getConnection();
const someQuery = await query(
connection,
"SELECT * FROM todos WHERE id = $1;",
[1],
);
await query(
connection,
\`
INSERT INTO
todos (id, description, done)
VALUES
($1, "todo description", TRUE);
\`,
[1],
);
})();
"
`;
2 changes: 2 additions & 0 deletions vsce-test/test-workspace-rs/src/diesel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ fn main() {
r#"
SELECT id, description, done
FROM todos
WHERE id = ?
ORDER BY id
"#,
)
.bind::<diesel::sql_types::Integer, _>(1)
.load::<model::User>(&conn)
.unwrap();
println!("{:?}", results);
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ afterEach(async () => {
]);
});

describe("SQLx Completion Test", () => {
describe("Completion Test", () => {
test('Should be completed "INSERT" with query! single line', async () => {
const filePath = path.resolve(wsPath, "src", "main.rs");
const docUri = vscode.Uri.file(filePath);
Expand Down Expand Up @@ -245,4 +245,34 @@ describe("Formatting Test", () => {
const formattedText = doc.getText();
expect(formattedText).toMatchSnapshot();
});

it("Should be formatted with diesel function", async () => {
const filePath = path.resolve(wsPath, "src", "diesel.rs");
const docUri = vscode.Uri.file(filePath);
const doc = await vscode.workspace.openTextDocument(docUri);
const editor = await vscode.window.showTextDocument(doc);

await sleep(1000);

// change config
await vscode.workspace
.getConfiguration("sqlsurge", vscode.workspace.workspaceFolders?.[0].uri)
.update("customRawSqlQuery", {
language: "rust",
configs: [
{
functionName: "sql_query",
sqlArgNo: 1,
isMacro: false,
},
],
});

// execute command
await vscode.commands.executeCommand("sqlsurge.formatSql");
await sleep(1000);

const formattedText = doc.getText();
expect(formattedText).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function run(

const config = {
testMatch: ["<rootDir>/out/suite-rs/*.test.js"],
testEnvironment: "./src/vscode-environment.ts",
testEnvironment: "./test/vscode-environment.ts",
} as Config.Argv;

const test = await runCLI(config, [projectRootPath]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,4 +221,34 @@ describe("Formatting Test", () => {
const formattedText = doc.getText();
expect(formattedText).toMatchSnapshot();
});

it("Should be formatted with user-defined function", async () => {
const filePath = path.resolve(wsPath, "src", "userDefined.ts");
const docUri = vscode.Uri.file(filePath);
const doc = await vscode.workspace.openTextDocument(docUri);
const editor = await vscode.window.showTextDocument(doc);

await sleep(1000);

// change config
await vscode.workspace
.getConfiguration("sqlsurge", vscode.workspace.workspaceFolders?.[0].uri)
.update("customRawSqlQuery", {
language: "typescript",
configs: [
{
functionName: "query",
sqlArgNo: 2,
isTemplateLiteral: false,
},
],
});

// execute command
await vscode.commands.executeCommand("sqlsurge.formatSql");
await sleep(1000);

const formattedText = doc.getText();
expect(formattedText).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function run(

const config = {
testMatch: ["<rootDir>/out/suite-ts/*.test.js"],
testEnvironment: "./src/vscode-environment.ts",
testEnvironment: "./test/vscode-environment.ts",
} as Config.Argv;

const test = await runCLI(config, [projectRootPath]);
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions vsce-test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"compilerOptions": {
"outDir": "out",
"rootDir": "src",
"rootDir": "test",
"esModuleInterop": false
},
"include": ["src"],
"include": ["test"],
"extends": "../tsconfig.json"
}
44 changes: 39 additions & 5 deletions vsce/src/commands/formatSql.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { SqlNode } from "@senken/config";

import { format } from "sql-formatter";
import * as ts from "typescript";
import * as vscode from "vscode";

import { getWorkspaceConfig } from "../extConfig";
import { createLogger } from "../outputChannel";

Expand Down Expand Up @@ -31,15 +33,47 @@ async function formatSql(refresh: RefreshFunc): Promise<void> {
editor.edit((editBuilder) => {
sqlNodes.map((sqlNode) => {
// get prefix and suffix of space or new line
const prefixMatch = sqlNode.content.match(/^(\s*)/);
const prefix = prefixMatch ? prefixMatch[0].replace(/ +$/g, "") : "";
const suffixMatch = sqlNode.content.match(/(\s*)$/);
const suffix = suffixMatch ? suffixMatch[0] : "";
const prefix =
sqlNode.content
.match(/^(\s*)/)?.[0]
.replace(/ +$/g, "") ?? // remove indent space
"";
const suffix = sqlNode.content.match(/(\s*)$/)?.[0] ?? "";

// skip typescript && "" or '' string(1 line)
const sourceText = document.getText();
const sourceFile = ts.createSourceFile(
"unusedFileName",
sourceText,
ts.ScriptTarget.Latest, // TODO: #74 re-consider this it should be the same as the vscode lsp or project tsconfig.json
);
const startPosition =
sourceFile.getPositionOfLineAndCharacter(
sqlNode.code_range.start.line,
sqlNode.code_range.start.character,
) - prefix.length;
const endPosition =
sourceFile.getPositionOfLineAndCharacter(
sqlNode.code_range.end.line,
sqlNode.code_range.end.character,
) + suffix.length;
if (
document.languageId === "typescript" &&
sourceText[startPosition - 1].match(/^["']$/) &&
sourceText[endPosition].match(/^["']$/)
) {
logger.debug(
"[formatSql]",
"Skip formatting for typescript string 1 line",
sqlNode,
);
return;
}

// convert place holder to dummy if there are any place holders
const placeHolderRegExp =
document.languageId === "typescript"
? /\$\{.*\}/g
? /\$(\{.*\}|\d+)/g // ${1} or $1
: document.languageId === "rust"
? /(\$\d+|\?)/g
: undefined;
Expand Down

0 comments on commit 228cf4c

Please sign in to comment.