repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -4,7 +4,7 @@ import { execSync, exec } from "child_process";
import { confirm } from "@clack/prompts";
import chalk from "chalk";
-// import { removeDirectory } from "./fileController";
+import { removeDirectory } from "./fileController"; | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在导入模块的时候,建议按照字母顺序进行排序,以提高代码的可读性和维护性。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -25,8 +25,9 @@ process.stdin.on("data", (key) => {
});
// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
+export default async function createAppTest(projectName: string, options: Record<string, any>) {
const rootDirectory = resolveApp(projectName);
+ console.log(!options.force, "options.force", fs.existsSync(rootDirectory)); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在创建项目文件夹之前,应该先检查`rootDirectory`是否已经存在。如果存在且未设置`force`选项,则应该显示确认提示。如果用户确认,再删除现有目录后再创建新目录。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -36,9 +37,15 @@ export default async function createAppTest(projectName: string, options) {
});
// 删除已存在文件并创建新文件
- console.log(shouldContinue);
+ if (shouldContinue === true) {
+ removeDirectory(rootDirectory, false);
+ } else {
+ process.exit(1);
+ }
- await execSync(`mkdir ${rootDirectory}`);
+ fs.mkdirSync(rootDirectory, { recursive: true });
+ } else {
+ fs.mkdirSync(rootDirectory, { recursive: true }); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在删除已存在文件并创建新文件的逻辑中,可以使用`fs.mkdirSync`替换`execSync`命令来创建目录。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | uaenaTzx | @@ -36,9 +37,15 @@ export default async function createAppTest(projectName: string, options) {
});
// 删除已存在文件并创建新文件
- console.log(shouldContinue);
+ if (shouldContinue === true) {
+ removeDirectory(rootDirectory, false);
+ } else {
+ process.exit(1);
+ }
- await execSync(`mkdir ${rootDirectory}`);
+ fs.mkdirSync(rootDirectory, { recursive: true }); | 这个独立出来不好吗,有点冗余 |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) { | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
`createFolder`函数的参数`options`类型为`Record<string, any>`,建议添加更具体的类型注解,以提高代码的可读性和可维护性。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) {
+ // 检查目录是否存在
+ if (fs.existsSync(rootDirectory)) {
+ let proceed = options.force; // 如果强制创建,则默认继续
+
+ // 如果不是强制创建,询问用户是否覆盖
+ if (!proceed) {
+ proceed = await confirm({
+ message:
+ "Whether to overwrite a file with the same name that exists in the current directory?",
+ }); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在询问用户是否覆盖同名文件时,建议提供更明确的提示信息,以便用户能够做出准确的选择。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) {
+ // 检查目录是否存在
+ if (fs.existsSync(rootDirectory)) {
+ let proceed = options.force; // 如果强制创建,则默认继续
+
+ // 如果不是强制创建,询问用户是否覆盖
+ if (!proceed) {
+ proceed = await confirm({
+ message:
+ "Whether to overwrite a file with the same name that exists in the current directory?",
+ });
+ }
- // 创建项目文件夹
- if (fs.existsSync(rootDirectory) && !options.force) {
- const shouldContinue = await confirm({
- message:
- "Whether to overwrite a file with the same name that exists in the current directory ?",
- });
+ // 根据用户的选择或强制选项决定是否继续
+ if (proceed) {
+ removeDirectory(rootDirectory, false); // 删除已存在的目录 | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
调用`removeDirectory`函数时,第二个参数传递了一个布尔值`false`,但是根据代码逻辑,应该传递`options.force`的值。请确认是否存在错误。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) {
+ // 检查目录是否存在
+ if (fs.existsSync(rootDirectory)) {
+ let proceed = options.force; // 如果强制创建,则默认继续
+
+ // 如果不是强制创建,询问用户是否覆盖
+ if (!proceed) {
+ proceed = await confirm({
+ message:
+ "Whether to overwrite a file with the same name that exists in the current directory?",
+ });
+ }
- // 创建项目文件夹
- if (fs.existsSync(rootDirectory) && !options.force) {
- const shouldContinue = await confirm({
- message:
- "Whether to overwrite a file with the same name that exists in the current directory ?",
- });
+ // 根据用户的选择或强制选项决定是否继续
+ if (proceed) {
+ removeDirectory(rootDirectory, false); // 删除已存在的目录
+ } else {
+ process.exit(1); // 用户选择不覆盖,退出程序 | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在用户选择不覆盖同名文件时,调用`process.exit(1)`退出程序可能会导致意外的行为。建议使用更合适的方式处理这种情况,例如抛出异常或返回错误码。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) {
+ // 检查目录是否存在
+ if (fs.existsSync(rootDirectory)) {
+ let proceed = options.force; // 如果强制创建,则默认继续
+
+ // 如果不是强制创建,询问用户是否覆盖
+ if (!proceed) {
+ proceed = await confirm({
+ message:
+ "Whether to overwrite a file with the same name that exists in the current directory?",
+ });
+ }
- // 创建项目文件夹
- if (fs.existsSync(rootDirectory) && !options.force) {
- const shouldContinue = await confirm({
- message:
- "Whether to overwrite a file with the same name that exists in the current directory ?",
- });
+ // 根据用户的选择或强制选项决定是否继续
+ if (proceed) {
+ removeDirectory(rootDirectory, false); // 删除已存在的目录
+ } else {
+ process.exit(1); // 用户选择不覆盖,退出程序
+ }
+ }
- // 删除已存在文件并创建新文件
- console.log(shouldContinue);
+ // 创建目录,如果之前已经删除或目录不存在
+ fs.mkdirSync(rootDirectory, { recursive: true }); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
创建目录时,使用了`fs.mkdirSync`方法,并传递了`{ recursive: true }`选项。请注意,`recursive`选项在Node.js版本10.12.0及以上才可用。如果要兼容较旧的Node.js版本,请确保在使用`recursive`选项之前进行检查。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) {
+ // 检查目录是否存在
+ if (fs.existsSync(rootDirectory)) {
+ let proceed = options.force; // 如果强制创建,则默认继续
+
+ // 如果不是强制创建,询问用户是否覆盖
+ if (!proceed) {
+ proceed = await confirm({
+ message:
+ "Whether to overwrite a file with the same name that exists in the current directory?",
+ });
+ }
- // 创建项目文件夹
- if (fs.existsSync(rootDirectory) && !options.force) {
- const shouldContinue = await confirm({
- message:
- "Whether to overwrite a file with the same name that exists in the current directory ?",
- });
+ // 根据用户的选择或强制选项决定是否继续
+ if (proceed) {
+ removeDirectory(rootDirectory, false); // 删除已存在的目录
+ } else {
+ process.exit(1); // 用户选择不覆盖,退出程序
+ }
+ }
- // 删除已存在文件并创建新文件
- console.log(shouldContinue);
+ // 创建目录,如果之前已经删除或目录不存在
+ fs.mkdirSync(rootDirectory, { recursive: true });
+}
- await execSync(`mkdir ${rootDirectory}`);
- }
+// 模板创建主函数
+export default async function createAppTest(projectName: string, options: Record<string, any>) { | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
`createAppTest`函数的参数`options`缺少类型注解,请添加相应的类型注解,以提高代码的可读性和可维护性。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 46 | xun082 | github-actions[bot] | @@ -24,22 +24,37 @@ process.stdin.on("data", (key) => {
}
});
-// 模板创建主函数
-export default async function createAppTest(projectName: string, options) {
- const rootDirectory = resolveApp(projectName);
+// 创建项目文件夹
+async function createFolder(rootDirectory: string, options: Record<string, any>) {
+ // 检查目录是否存在
+ if (fs.existsSync(rootDirectory)) {
+ let proceed = options.force; // 如果强制创建,则默认继续
+
+ // 如果不是强制创建,询问用户是否覆盖
+ if (!proceed) {
+ proceed = await confirm({
+ message:
+ "Whether to overwrite a file with the same name that exists in the current directory?",
+ });
+ }
- // 创建项目文件夹
- if (fs.existsSync(rootDirectory) && !options.force) {
- const shouldContinue = await confirm({
- message:
- "Whether to overwrite a file with the same name that exists in the current directory ?",
- });
+ // 根据用户的选择或强制选项决定是否继续
+ if (proceed) {
+ removeDirectory(rootDirectory, false); // 删除已存在的目录
+ } else {
+ process.exit(1); // 用户选择不覆盖,退出程序
+ }
+ }
- // 删除已存在文件并创建新文件
- console.log(shouldContinue);
+ // 创建目录,如果之前已经删除或目录不存在
+ fs.mkdirSync(rootDirectory, { recursive: true });
+}
- await execSync(`mkdir ${rootDirectory}`);
- }
+// 模板创建主函数
+export default async function createAppTest(projectName: string, options: Record<string, any>) {
+ const rootDirectory = resolveApp(projectName);
+
+ await createFolder(rootDirectory, options); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
调用`createFolder`函数时,第二个参数传递了`options`,但是在旧代码中并没有传递该参数。请确认是否存在错误。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 42 | xun082 | github-actions[bot] | @@ -8,10 +8,6 @@ import { join } from "node:path";
import { packageVersion } from "./constants";
-/**
- * @param directoryPath 删除文件的路径,默认 node_modules
- * @param verbose 如果为true,则显示删除信息
- */
/**
* @author moment
* @param directoryPath 删除文件的路径,默认 node_modules | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在`fileController.ts`文件中,删除了一个注释块和一个参数说明的注释。这可能会导致其他开发人员对该函数的理解产生困惑。建议保留参数说明的注释以提供更多的上下文信息。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 39 | xun082 | github-actions[bot] | @@ -4,10 +4,11 @@ import { execSync, exec } from "child_process";
import { confirm } from "@clack/prompts";
import chalk from "chalk";
-import { removeDirectory } from "./fileController";
+// import { removeDirectory } from "./fileController";
import { projectSelect } from "./select";
import isGitInstalled from "./checkGitInstallation";
// import { createPackageJson } from "./createFile"; | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
这里注释掉了`removeDirectory`的调用,但是没有提供替代的代码。请确认是否有意为之。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 39 | xun082 | github-actions[bot] | @@ -4,10 +4,11 @@ import { execSync, exec } from "child_process";
import { confirm } from "@clack/prompts";
import chalk from "chalk";
-import { removeDirectory } from "./fileController";
+// import { removeDirectory } from "./fileController";
import { projectSelect } from "./select";
import isGitInstalled from "./checkGitInstallation";
// import { createPackageJson } from "./createFile";
+import PackageAPI from "./packageAPI";
import { createFiles } from "./createFiles";
import { type Preset, getFilesForProject, getNpmForPackage } from "./preset";
import createSuccessInfo from "./createSuccessInfo"; | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
> Note: This review was outside of the patch, but no patch was found that overlapped with it. Original lines [22-23]
这里创建了一个`Preset`对象,但是没有使用它。请确认是否有意为之。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 39 | xun082 | github-actions[bot] | @@ -36,21 +37,34 @@ export default async function createAppTest(projectName: string, options) {
});
// 删除已存在文件并创建新文件
- if (shouldContinue === true) {
- removeDirectory(projectName, true);
- } else process.exit(1);
+ console.log(shouldContinue);
execSync(`mkdir ${rootDirectory}`); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
这里使用了`execSync`来执行命令`mkdir`,但是没有处理可能的异常情况。建议添加错误处理逻辑。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 39 | xun082 | github-actions[bot] | @@ -36,21 +37,34 @@ export default async function createAppTest(projectName: string, options) {
});
// 删除已存在文件并创建新文件
- if (shouldContinue === true) {
- removeDirectory(projectName, true);
- } else process.exit(1);
+ console.log(shouldContinue);
execSync(`mkdir ${rootDirectory}`);
}
// 获取用户选择预设
const preset: Preset = await projectSelect();
- console.log(rootDirectory);
// 创建package.json
- await createFiles(rootDirectory, {
- "package.json": "{}", // todo:具体内容待重构
+ console.log(chalk.blue(`\n📄 Generating package.json...`));
+ const packageContent = {
+ name: projectName,
+ version: "0.1.0",
+ private: true,
+ devDependencies: {},
+ };
+ // 遍历 preset.plugins,插入依赖
+ Object.keys(preset.plugins).forEach((dep) => {
+ console.log("dep:", dep);
+ // todo: 更多的处理依据 preset.plugins[dep] 后续的变化而插入
+ let { version } = preset.plugins[dep];
+ if (!version) {
+ version = "latest";
+ }
+ packageContent.devDependencies[dep] = version;
});
+ const packageJson = new PackageAPI(rootDirectory);
+ await packageJson.createPackageJson(packageContent); | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在这个代码块中,创建了一个`packageContent`对象,并将其传递给`PackageAPI`类的`createPackageJson`方法。然而,在新的代码中,没有展示如何使用`PackageAPI`类的实例。请提供相关的代码以确保`createPackageJson`方法被正确调用。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
create-neat | github_2023 | typescript | 39 | xun082 | github-actions[bot] | @@ -62,10 +76,10 @@ export default async function createAppTest(projectName: string, options) {
// todo: 插件未开发,先模拟过程
// 安装插件至 package.json
- Object.keys(preset.plugins).forEach(async (plugin) => {
- console.log(plugin, "installed");
+ Object.keys(packageContent.devDependencies).forEach(async (dep) => {
+ console.log(dep, "installed");
// 进入仓库
- // await execSync(`npm install ${plugin}`)
+ // await execSync(`npm install ${dep}`) | <img src="https://avatars.githubusercontent.com/in/347564?s=41" alt="Image description" width="20" height="20"> CodeRabbit
在这个代码块中,遍历了`packageContent.devDependencies`对象的键,并打印了每个键。然而,在新的代码中,没有展示如何安装依赖项。请提供相关的代码以确保依赖项被正确安装。
102:
这里打印了生成README.md文件的消息,但是没有展示具体的文件内容和创建过程。请提供相关的代码以确保README.md文件被正确创建。
以上是对`packages/core/src/utils/createAppTest.ts`文件的代码审查。请注意,这些评论仅针对代码质量和潜在问题,不包括其他方面的细节。
<!-- This is an auto-generated comment by OSS CodeRabbit --> |
nextjs-openai-doc-search | github_2023 | others | 35 | supabase-community | thorwebdev | @@ -6,7 +6,7 @@ This starter takes all the `.mdx` files in the `pages` directory and processes t
Deploy this starter to Vercel. The Supabase integration will automatically set the required environment variables and configure your [Database Schema](./supabase/migrations/20230406025118_init.sql). All you have to do is set your `OPENAI_KEY` and you're ready to go!
-[](https://vercel.com/new/clone?demo-title=Next.js%20OpenAI%20Doc%20Search%20Starter&demo-description=Template%20for%20building%20your%20own%20custom%20ChatGPT%20style%20doc%20search%20powered%20by%20Next.js%2C%20OpenAI%2C%20and%20Supabase.&demo-url=https%3A%2F%2Fsupabase.com%2Fdocs&demo-image=%2F%2Fimages.ctfassets.net%2Fe5382hct74si%2F1OntM6THNEUvlUsYy6Bjmf%2F475e39dbc84779538c8ed47c63a37e0e%2Fnextjs_openai_doc_search_og.png&project-name=Next.js%20OpenAI%20Doc%20Search%20Starter&repository-name=nextjs-openai-doc-search-starter&repository-url=https%3A%2F%2Fgithub.com%2Fsupabase-community%2Fnextjs-openai-doc-search%2F&from=github&integration-ids=oac_jUduyjQgOyzev1fjrW83NYOv&env=OPENAI_KEY&envDescription=Get%20your%20OpenAI%20API%20key%3A&envLink=https%3A%2F%2Fplatform.openai.com%2Faccount%2Fapi-keys&teamCreateStatus=hidden&external-id=nextjs-open-ai-doc-search)
+[](https://vercel.com/new/clone?demo-title=Next.js%20OpenAI%20Doc%20Search%20Starter&demo-description=Template%20for%20building%20your%20own%20custom%20ChatGPT%20style%20doc%20search%20powered%20by%20Next.js%2C%20OpenAI%2C%20and%20Supabase.&demo-url=https%3A%2F%2Fsupabase.com%2Fdocs&demo-image=%2F%2Fimages.ctfassets.net%2Fe5382hct74si%2F1OntM6THNEUvlUsYy6Bjmf%2F475e39dbc84779538c8ed47c63a37e0e%2Fnextjs_openai_doc_search_og.png&project-name=Next.js%20OpenAI%20Doc%20Search%20Starter&repository-name=nextjs-openai-doc-search-starter&repository-url=https%3A%2F%2Fgithub.com%2Fsupabase-community%2Fnextjs-openai-doc-search%2F&from=github&integration-ids=oac_VqOgBHqhEoFTPzGkPd7L0iH6&env=OPENAI_KEY&envDescription=Get%20your%20OpenAI%20API%20key%3A&envLink=https%3A%2F%2Fplatform.openai.com%2Faccount%2Fapi-keys&teamCreateStatus=hidden&external-id=nextjs-open-ai-doc-search) | @MildTomato does `external-id=nextjs-open-ai-doc-search` still work for v2 or do we need to update it to `https://github.com/supabase-community/nextjs-openai-doc-search/tree/main`? |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -80,6 +82,12 @@ Make sure you have Docker installed and running locally. Then run
supabase start
```
+To retrieve ```NEXT_PUBLIC_SUPABASE_ANON_KEY``` and ```SUPABASE_SERVICE_ROLE_KEY``` you have to run | ```suggestion
To retrieve `NEXT_PUBLIC_SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_ROLE_KEY` run:
``` |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -69,8 +69,10 @@ The initialization of the database, including the setup of the `pgvector` extens
### Configuration
-- `cp .env.example .env`
+- `cp .env.example .env` or rename `.env.example` into .env
- Set your `OPENAI_KEY` in the newly created `.env` file.
+- Set ```NEXT_PUBLIC_SUPABASE_ANON_KEY``` and ```SUPABASE_SERVICE_ROLE_KEY``` in .env | ```suggestion
- Set `NEXT_PUBLIC_SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_ROLE_KEY` in `.env`
``` |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -69,8 +69,10 @@ The initialization of the database, including the setup of the `pgvector` extens
### Configuration
-- `cp .env.example .env`
+- `cp .env.example .env` or rename `.env.example` into .env | Might be best to stick with the `cp` for documentation purposes in case users want to fork/continue using this git repo. (`.env` shouldn't be committed to source control with creds/secrets so typically you would leave the `.env.example` in the repo). |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -88,6 +96,13 @@ In a new terminal window, run
pnpm dev
```
+### Using your custom .mdx docs
+1. Make sure your documentation is in .mdx format. This can be done by renaming exisiting(or compatible) markdown .md file | ```suggestion
1. By default your documentation will need to be in `.mdx` format. This can be done by renaming existing (or compatible) markdown `.md` file.
``` |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -88,6 +96,13 @@ In a new terminal window, run
pnpm dev
```
+### Using your custom .mdx docs
+1. Make sure your documentation is in .mdx format. This can be done by renaming exisiting(or compatible) markdown .md file
+2. Run ```pnpm run embeddings``` to regenerate embeddings. | ```suggestion
2. Run `pnpm run embeddings` to regenerate embeddings.
``` |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -88,6 +96,13 @@ In a new terminal window, run
pnpm dev
```
+### Using your custom .mdx docs
+1. Make sure your documentation is in .mdx format. This can be done by renaming exisiting(or compatible) markdown .md file
+2. Run ```pnpm run embeddings``` to regenerate embeddings.
+>Note: Make sure supabase is running. To check, run ```supabase status```. If is not running run ```supabase start``` | ```suggestion
> Note: Make sure supabase is running. To check, run `supabase status`. If is not running run `supabase start`.
``` |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -88,6 +96,13 @@ In a new terminal window, run
pnpm dev
```
+### Using your custom .mdx docs
+1. Make sure your documentation is in .mdx format. This can be done by renaming exisiting(or compatible) markdown .md file
+2. Run ```pnpm run embeddings``` to regenerate embeddings.
+>Note: Make sure supabase is running. To check, run ```supabase status```. If is not running run ```supabase start```
+3. Run ```pnpm dev``` again to refresh NextJS localhost:3000 rendered page. | ```suggestion
3. Run `pnpm dev` again to refresh NextJS localhost:3000 rendered page.
``` |
nextjs-openai-doc-search | github_2023 | others | 29 | supabase-community | gregnr | @@ -88,6 +96,12 @@ In a new terminal window, run
pnpm dev
```
+### Using your custom .mdx docs
+1. By default your documentation will need to be in `.mdx` format. This can be done by renaming existing (or compatible) markdown `.md` file.
+2. Run `pnpm run embeddings` to regenerate embeddings.
+> Note: Make sure supabase is running. To check, run `supabase status`. If is not running run `supabase start`. | ```suggestion
> Note: Make sure supabase is running. To check, run `supabase status`. If is not running run `supabase start`.
``` |
nextjs-openai-doc-search | github_2023 | others | 25 | supabase-community | gregnr | @@ -8,7 +8,8 @@
"start": "next start",
"lint": "next lint",
"format": "prettier --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\"",
- "embeddings": "tsx lib/generate-embeddings.ts"
+ "embeddings": "tsx lib/generate-embeddings.ts",
+ "embeddings:r": "tsx lib/generate-embeddings.ts --refresh" | ```suggestion
"embeddings:refresh": "tsx lib/generate-embeddings.ts --refresh"
``` |
supabase-go | github_2023 | go | 11 | supabase-community | tranhoangvuit | @@ -2,35 +2,49 @@ package supabase
import (
"errors"
+ "log"
+ "time"
+ "github.com/supabase-community/functions-go"
+ "github.com/supabase-community/gotrue-go"
+ "github.com/supabase-community/gotrue-go/types"
+ postgrest "github.com/supabase-community/postgrest-go"
storage_go "github.com/supabase-community/storage-go"
- "github.com/supabase/postgrest-go"
)
const (
- REST_URL = "/rest/v1"
- STORGAGE_URL = "/storage/v1"
+ REST_URL = "/rest/v1"
+ STORGAGE_URL = "/storage/v1"
+ AUTH_URL = "/auth/v1"
+ FUNCTIONS_URL = "/functions/v1"
)
type Client struct {
+ // Why is this a private field?? | Because we already implemented two main function of rest in this lib, so we don't need to call via `.Rest`. It's same idea with `supabase-js`
If it's okie, can you remove this comment? |
supabase-go | github_2023 | go | 11 | supabase-community | tranhoangvuit | @@ -76,3 +93,74 @@ func (c *Client) From(table string) *postgrest.QueryBuilder {
func (c *Client) Rpc(name, count string, rpcBody interface{}) string {
return c.rest.Rpc(name, count, rpcBody)
}
+
+func (c *Client) SignInWithEmailPassword(email, password string) (types.Session, error) { | can you move these function to auth package here? https://github.com/supabase-community/gotrue-go |
supabase-go | github_2023 | go | 9 | supabase-community | tranhoangvuit | @@ -3,64 +3,70 @@ package supabase
import (
"errors"
+ "github.com/supabase-community/gotrue-go"
+ "github.com/supabase-community/gotrue-go/types"
+ postgrest "github.com/supabase-community/postgrest-go"
storage_go "github.com/supabase-community/storage-go"
- "github.com/supabase/postgrest-go"
)
const (
REST_URL = "/rest/v1"
STORGAGE_URL = "/storage/v1"
+ AUTH_URL = "/auth/v1"
)
type Client struct {
- rest *postgrest.Client
- Storage *storage_go.Client
+ // Why is this a private field??
+ rest postgrest.Client
+ Storage storage_go.Client
+ Auth gotrue.Client
+ options clientOptions
}
-type RestOptions struct {
- Schema string
-}
-
-type ClientOptions struct {
- Headers map[string]string
- Db *RestOptions
+type clientOptions struct {
+ url string
+ headers map[string]string
}
// NewClient creates a new Supabase client.
// url is the Supabase URL.
// key is the Supabase API key.
// options is the Supabase client options.
-func NewClient(url, key string, options *ClientOptions) (*Client, error) {
+func NewClient(url, key string, schema string, headers map[string]string) (*Client, error) { | I think we should heep it in struct will be better, in the feature, if we have more fields, we can put it in struct instead of parameters.
The second issue, I want to make it consistent format with `supabase-js` library:
```
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', {
global: {
fetch: (...args) => fetch(...args),
},
})
``` |
supabase-go | github_2023 | go | 9 | supabase-community | tranhoangvuit | @@ -3,64 +3,70 @@ package supabase
import (
"errors"
+ "github.com/supabase-community/gotrue-go"
+ "github.com/supabase-community/gotrue-go/types"
+ postgrest "github.com/supabase-community/postgrest-go"
storage_go "github.com/supabase-community/storage-go"
- "github.com/supabase/postgrest-go"
)
const (
REST_URL = "/rest/v1"
STORGAGE_URL = "/storage/v1"
+ AUTH_URL = "/auth/v1"
)
type Client struct {
- rest *postgrest.Client
- Storage *storage_go.Client
+ // Why is this a private field??
+ rest postgrest.Client
+ Storage storage_go.Client
+ Auth gotrue.Client
+ options clientOptions
}
-type RestOptions struct {
- Schema string
-}
-
-type ClientOptions struct {
- Headers map[string]string
- Db *RestOptions
+type clientOptions struct {
+ url string
+ headers map[string]string
}
// NewClient creates a new Supabase client.
// url is the Supabase URL.
// key is the Supabase API key.
// options is the Supabase client options.
-func NewClient(url, key string, options *ClientOptions) (*Client, error) {
+func NewClient(url, key string, schema string, headers map[string]string) (*Client, error) {
if url == "" || key == "" {
return nil, errors.New("url and key are required")
}
- headers := map[string]string{
- "Authorization": "Bearer " + key,
- "apikey": key,
+ if headers == nil {
+ headers = map[string]string{}
}
- if options != nil && options.Headers != nil {
- for k, v := range options.Headers {
+ headers["Authorization"] = "Bearer " + key
+ headers["apikey"] = key
+
+ if headers != nil {
+ for k, v := range headers {
headers[k] = v
}
}
- var schema string
- if options != nil && options.Db != nil && options.Db.Schema != "" {
- schema = options.Db.Schema
- } else {
+ client := &Client{}
+ client.options.url = url
+ // map is pass by reference, so this gets updated by rest of function
+ client.options.headers = headers
+
+ if schema == "" {
schema = "public"
}
- if options != nil && options.Headers != nil { | Thanks, let remove it. |
supabase-go | github_2023 | go | 9 | supabase-community | tranhoangvuit | @@ -3,64 +3,68 @@ package supabase
import (
"errors"
+ "github.com/supabase-community/gotrue-go"
+ "github.com/supabase-community/gotrue-go/types"
+ postgrest "github.com/supabase-community/postgrest-go"
storage_go "github.com/supabase-community/storage-go"
- "github.com/supabase/postgrest-go"
)
const (
REST_URL = "/rest/v1"
STORGAGE_URL = "/storage/v1"
+ AUTH_URL = "/auth/v1"
)
type Client struct {
+ // Why is this a private field??
rest *postgrest.Client
Storage *storage_go.Client
+ // Auth is an interface. We don't need a pointer to an interface.
+ Auth gotrue.Client
+ options clientOptions
}
-type RestOptions struct {
- Schema string
-}
-
-type ClientOptions struct {
- Headers map[string]string
- Db *RestOptions
+type clientOptions struct {
+ url string
+ headers map[string]string
}
// NewClient creates a new Supabase client.
// url is the Supabase URL.
// key is the Supabase API key.
// options is the Supabase client options.
-func NewClient(url, key string, options *ClientOptions) (*Client, error) {
+func NewClient(url, key string, schema string, headers map[string]string) (*Client, error) {
if url == "" || key == "" {
return nil, errors.New("url and key are required")
}
- headers := map[string]string{
- "Authorization": "Bearer " + key,
- "apikey": key,
+ if headers == nil { | It seems that the new code is the same as the old one if we continue to use a struct as a parameter. |
supabase-go | github_2023 | go | 9 | supabase-community | tranhoangvuit | @@ -76,3 +87,39 @@ func (c *Client) From(table string) *postgrest.QueryBuilder {
func (c *Client) Rpc(name, count string, rpcBody interface{}) string {
return c.rest.Rpc(name, count, rpcBody)
}
+
+func (c *Client) SignInWithEmailPassword(email, password string) error { | We will merge this first, but it will be removed soon, because it should belong to auth. |
postgres_lsp | github_2023 | others | 257 | supabase-community | psteinroe | @@ -0,0 +1,26 @@
+use crate::session::Session;
+use pgt_text_size::TextSize;
+use tower_lsp::lsp_types;
+
+pub fn get_cursor_position( | maybe we can just put the "converter" create into the lsp crate and then put this one alongside everything else |
postgres_lsp | github_2023 | others | 257 | supabase-community | psteinroe | @@ -0,0 +1,114 @@
+use crate::session::Session;
+use anyhow::{Result, anyhow};
+use tower_lsp::lsp_types::{
+ self, CodeAction, CodeActionDisabled, CodeActionOrCommand, Command, ExecuteCommandParams,
+ MessageType,
+};
+
+use pgt_workspace::code_actions::{
+ CodeActionKind, CodeActionsParams, CommandActionCategory, ExecuteStatementParams,
+};
+
+use super::helper;
+
+pub fn get_actions(
+ session: &Session,
+ params: lsp_types::CodeActionParams,
+) -> Result<lsp_types::CodeActionResponse> {
+ let url = params.text_document.uri;
+ let path = session.file_path(&url)?;
+
+ let cursor_position = helper::get_cursor_position(session, &url, params.range.start)?;
+
+ let workspace_actions = session.workspace.pull_code_actions(CodeActionsParams {
+ path,
+ cursor_position,
+ only: vec![],
+ skip: vec![],
+ })?;
+
+ let actions: Vec<CodeAction> = workspace_actions
+ .actions
+ .into_iter()
+ .filter_map(|action| match action.kind {
+ CodeActionKind::Command(command) => {
+ let command_id: String = command_id(&command.category);
+ let title = action.title;
+
+ match command.category {
+ CommandActionCategory::ExecuteStatement(stmt_id) => Some(CodeAction {
+ title: title.clone(),
+ kind: Some(lsp_types::CodeActionKind::EMPTY),
+ command: Some({
+ Command {
+ title: title.clone(),
+ command: command_id,
+ arguments: Some(vec![
+ serde_json::Value::Number(stmt_id.into()),
+ serde_json::to_value(&url).unwrap(),
+ ]),
+ }
+ }),
+ disabled: action
+ .disabled_reason
+ .map(|reason| CodeActionDisabled { reason }),
+ ..Default::default()
+ }),
+ }
+ }
+
+ _ => todo!(),
+ })
+ .collect();
+
+ Ok(actions
+ .into_iter()
+ .map(|ac| CodeActionOrCommand::CodeAction(ac))
+ .collect())
+}
+
+pub fn command_id(command: &CommandActionCategory) -> String {
+ match command {
+ CommandActionCategory::ExecuteStatement(_) => "pgt.executeStatement".into(),
+ }
+}
+
+pub async fn execute_command(
+ session: &Session,
+ params: ExecuteCommandParams,
+) -> anyhow::Result<Option<serde_json::Value>> {
+ let command = params.command;
+
+ match command.as_str() {
+ "pgt.executeStatement" => {
+ let id: usize = serde_json::from_value(params.arguments[0].clone())?;
+ let doc_url: lsp_types::Url = serde_json::from_value(params.arguments[1].clone())?;
+
+ let path = session.file_path(&doc_url)?;
+
+ let result = session
+ .workspace
+ .execute_statement(ExecuteStatementParams {
+ statement_id: id,
+ path,
+ })?;
+
+ /**
+ * Updating all diagnostics: the changes caused by the statement execution
+ * might affect many files.
+ *
+ * TODO: in test.sql, this seems to work after create table, but not after drop table.
+ */ | dont we need to invalidate the schema cache for this? |
postgres_lsp | github_2023 | others | 257 | supabase-community | psteinroe | @@ -0,0 +1,65 @@
+use crate::workspace::StatementId;
+use pgt_configuration::RuleSelector;
+use pgt_fs::PgTPath;
+use pgt_text_size::TextSize;
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
+pub struct CodeActionsParams {
+ pub path: PgTPath,
+ pub cursor_position: TextSize,
+ pub only: Vec<RuleSelector>,
+ pub skip: Vec<RuleSelector>,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
+pub struct CodeActionsResult {
+ pub actions: Vec<CodeAction>,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
+pub struct CodeAction {
+ pub title: String,
+ pub kind: CodeActionKind,
+ pub disabled_reason: Option<String>,
+}
+ | maybe we can put this in to a `features/` directory? we could also structure the other feature params and types in a similar manner. |
postgres_lsp | github_2023 | others | 257 | supabase-community | psteinroe | @@ -253,6 +259,88 @@ impl Workspace for WorkspaceServer {
Ok(self.is_ignored(params.pgt_path.as_path()))
}
+ fn pull_code_actions(
+ &self,
+ params: code_actions::CodeActionsParams,
+ ) -> Result<code_actions::CodeActionsResult, WorkspaceError> {
+ let doc = self
+ .documents
+ .get(¶ms.path)
+ .ok_or(WorkspaceError::not_found())?;
+
+ let eligible_statements = doc
+ .iter_statements_with_text_and_range()
+ .filter(|(_, range, _)| range.contains(params.cursor_position));
+ | we should check that the statement is valid by checking if there is a pg_query AST for it |
postgres_lsp | github_2023 | others | 259 | supabase-community | juleswritescode | @@ -88,9 +102,48 @@ Make sure to check out the other options. We will provide guides for specific us
We recommend installing an editor plugin to get the most out of Postgres Language Tools.
-> [!NOTE]
-> We will update this section once we have published the binaries.
+### VSCode
+
+TODO
+
+### Neovim
+
+You will have to install `nvim-lspconfig`, and follow the [instructions](https://github.com/neovim/nvim-lspconfig/blob/master/doc/configs.md#postgres_lsp).
+
+
+### Other
+
+Postgres Tools has LSP first-class support. If your editor does implement LSP, then the integration of Postgres Tools should be seamless.
+
+#### Use the LSP Proxy
+
+Postgres Tools has a command called `lsp-proxy`. When executed, two processes will spawn:
+- a daemon that does execute the requested operations;
+- a server that functions as a proxy between the requests of the client - the editor - and the server - the daemon;
+If your editor is able to interact with a server and send [JSON-RPC](https://www.jsonrpc.org) request, you only need to configure the editor run that command. | ```suggestion
If your editor is able to interact with a server and send [JSON-RPC](https://www.jsonrpc.org) requests, you only need to configure the editor to run that command.
``` |
postgres_lsp | github_2023 | others | 259 | supabase-community | juleswritescode | @@ -88,9 +102,48 @@ Make sure to check out the other options. We will provide guides for specific us
We recommend installing an editor plugin to get the most out of Postgres Language Tools.
-> [!NOTE]
-> We will update this section once we have published the binaries.
+### VSCode
+
+TODO
+
+### Neovim
+
+You will have to install `nvim-lspconfig`, and follow the [instructions](https://github.com/neovim/nvim-lspconfig/blob/master/doc/configs.md#postgres_lsp).
+
+
+### Other
+
+Postgres Tools has LSP first-class support. If your editor does implement LSP, then the integration of Postgres Tools should be seamless.
+
+#### Use the LSP Proxy
+
+Postgres Tools has a command called `lsp-proxy`. When executed, two processes will spawn:
+- a daemon that does execute the requested operations;
+- a server that functions as a proxy between the requests of the client - the editor - and the server - the daemon;
+If your editor is able to interact with a server and send [JSON-RPC](https://www.jsonrpc.org) request, you only need to configure the editor run that command.
+
+#### Use the daemon with the binary
+Using the binary via CLI is very efficient, although you won’t be able to provide logs to your users. The CLI allows you to bootstrap a daemon and then use the CLI commands through the daemon itself.
+If order to do so, you first need to start a daemon process with the start command: | ```suggestion
In order to do so, you first need to start a daemon process with the start command:
``` |
postgres_lsp | github_2023 | others | 259 | supabase-community | juleswritescode | @@ -88,9 +102,48 @@ Make sure to check out the other options. We will provide guides for specific us
We recommend installing an editor plugin to get the most out of Postgres Language Tools.
-> [!NOTE]
-> We will update this section once we have published the binaries.
+### VSCode
+
+TODO
+
+### Neovim
+
+You will have to install `nvim-lspconfig`, and follow the [instructions](https://github.com/neovim/nvim-lspconfig/blob/master/doc/configs.md#postgres_lsp).
+
+
+### Other
+
+Postgres Tools has LSP first-class support. If your editor does implement LSP, then the integration of Postgres Tools should be seamless.
+
+#### Use the LSP Proxy
+
+Postgres Tools has a command called `lsp-proxy`. When executed, two processes will spawn:
+- a daemon that does execute the requested operations;
+- a server that functions as a proxy between the requests of the client - the editor - and the server - the daemon;
+If your editor is able to interact with a server and send [JSON-RPC](https://www.jsonrpc.org) request, you only need to configure the editor run that command.
+
+#### Use the daemon with the binary
+Using the binary via CLI is very efficient, although you won’t be able to provide logs to your users. The CLI allows you to bootstrap a daemon and then use the CLI commands through the daemon itself.
+If order to do so, you first need to start a daemon process with the start command:
+
+```sh
+postgrestools start
+```
+
+Then, every command needs to add the `--use-server` options, e.g.:
+
+```sh
+echo "select 1" | biome check --use-server --stdin-file-path=dummy.sql
+```
+
+#### Daemon logs
+The daemon saves logs in your file system. Logs are stored in a folder called `pgt-logs`. The path of this folder changes based on your operative system:
+
+- Linux: `~/.cache/pgt;`
+- Windows: `C:\Users\<UserName>\AppData\Local\supabase-community\pgt\cache`
+- macOS: `/Users/<UserName>/Library/Caches/dev.supabase-community.pgt`
+For other operative systems, you can find the folder in the system’s temporary directory. | ```suggestion
For other operative systems, you can find the folder in the system’s temporary directory.
You can change the location of the `pgt-logs` folder via the `PGT_LOG_PATH` variable.
``` |
postgres_lsp | github_2023 | others | 259 | supabase-community | juleswritescode | @@ -88,9 +102,48 @@ Make sure to check out the other options. We will provide guides for specific us
We recommend installing an editor plugin to get the most out of Postgres Language Tools.
-> [!NOTE]
-> We will update this section once we have published the binaries.
+### VSCode
+
+TODO
+
+### Neovim
+
+You will have to install `nvim-lspconfig`, and follow the [instructions](https://github.com/neovim/nvim-lspconfig/blob/master/doc/configs.md#postgres_lsp).
+
+
+### Other
+
+Postgres Tools has LSP first-class support. If your editor does implement LSP, then the integration of Postgres Tools should be seamless. | ```suggestion
Postgres Tools has first-class LSP support. If your editor does implement LSP, then the integration of Postgres Tools should be seamless.
``` |
postgres_lsp | github_2023 | others | 259 | supabase-community | juleswritescode | @@ -25,8 +25,22 @@ Our current focus is on refining and enhancing these core features while buildin
## Installation
-> [!NOTE]
-> We will update this section once we have published the binaries.
+To install Postgres Tools, grab the executable for your platform from the [latest CLI release](https://github.com/supabase-community/postgres_lsp/releases) on GitHub and give it execution permission. | ```suggestion
To install Postgres Tools, grab the executable for your platform from the [latest CLI release](https://github.com/supabase-community/postgres_lsp/releases/latest) on GitHub and give it execution permission.
``` |
postgres_lsp | github_2023 | others | 259 | supabase-community | juleswritescode | @@ -25,8 +25,22 @@ Our current focus is on refining and enhancing these core features while buildin
## Installation
-> [!NOTE]
-> We will update this section once we have published the binaries.
+To install Postgres Tools, grab the executable for your platform from the [latest CLI release](https://github.com/supabase-community/postgres_lsp/releases) on GitHub and give it execution permission.
+
+```sh
+curl -L https://github.com/supabase-community/postgres_lsp/releases/download/<version>/postgrestools_aarch64-apple-darwin -o postgrestools
+chmod +x postgrestools
+```
+
+Now you can use Postgres Tools by simply running `./postgrestools`.
+
+If you are using Node anyways, you can also install the CLI via NPM. Run the following commands in a directory containing a `package.json` file. | ```suggestion
If you are using Node, you can also install the CLI via NPM. Run the following commands in a directory containing a `package.json` file.
``` |
postgres_lsp | github_2023 | others | 255 | supabase-community | juleswritescode | @@ -441,7 +441,7 @@ async fn server_shutdown() -> Result<()> {
let cancellation = factory.cancellation();
let cancellation = cancellation.notified();
- // this is called when `pglt stop` is run by the user
+ // this is called when `pgt stop` is run by the user | ```suggestion
// this is called when `postgrestools stop` is run by the user
``` |
postgres_lsp | github_2023 | others | 240 | supabase-community | juleswritescode | @@ -41,6 +41,7 @@ After running the `init` command, you’ll have a `pglt.jsonc` file in your dire
```json
{
+ "": "https://supabase-community.github.io/postgres_lsp/schemas/0.0.0/schema.json", | sollte der key nicht $schema sein? |
postgres_lsp | github_2023 | others | 240 | supabase-community | juleswritescode | @@ -11,33 +11,34 @@ install-tools:
cargo install cargo-binstall
cargo binstall cargo-insta taplo-cli
cargo binstall --git "https://github.com/astral-sh/uv" uv
-
+ bun install
# Upgrades the tools needed to develop
upgrade-tools:
cargo install cargo-binstall --force
- cargo binstall cargo-insta taplo-cli --force
+ cargo binstall cargo-insta taplo-cli wasm-pack wasm-tools --force | ist der wasm kram noch n überbleibsel von deinen versuchen? |
postgres_lsp | github_2023 | others | 240 | supabase-community | juleswritescode | @@ -11,33 +11,34 @@ install-tools:
cargo install cargo-binstall
cargo binstall cargo-insta taplo-cli
cargo binstall --git "https://github.com/astral-sh/uv" uv
-
+ bun install | funktioniert das lokal, wenn in der `bun.lock` die ganzen `<placeholder>` values stehen? |
postgres_lsp | github_2023 | others | 240 | supabase-community | juleswritescode | @@ -0,0 +1,34 @@
+{
+ "name": "@pglt/backend-jsonrpc",
+ "version": "<placeholder>",
+ "main": "dist/index.js",
+ "scripts": {
+ "test": "bun test",
+ "test:ci": "bun build && bun test",
+ "build": "bun build ./src/index.ts --outdir ./dist --target node"
+ },
+ "files": ["dist/", "README.md"],
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/supabase-community/postgres_lsp.git",
+ "directory": "packages/@pglt/backend-jsonrpc"
+ },
+ "author": "Supabase Community",
+ "bugs": "ttps://github.com/supabase-community/postgres_lsp/issues",
+ "description": "Bindings to the JSON-RPC Workspace API of the Postgres Language Tools daemon",
+ "keywords": ["TypeScript", "Postgres"],
+ "license": "MIT",
+ "publishConfig": {
+ "provenance": true
+ },
+ "optionalDependencies": {
+ "@pglt/cli-win32-x64": "<placeholder>",
+ "@pglt/cli-win32-arm64": "<placeholder>",
+ "@pglt/cli-darwin-x64": "<placeholder>",
+ "@pglt/cli-darwin-arm64": "<placeholder>",
+ "@pglt/cli-linux-x64": "<placeholder>",
+ "@pglt/cli-linux-arm64": "<placeholder>",
+ "@pglt/cli-linux-x64-musl": "<placeholder>",
+ "@pglt/cli-linux-arm64-musl": "<placeholder>" | die `musl's` sind bisher nicht supported in `generate-package.mjs` |
postgres_lsp | github_2023 | typescript | 240 | supabase-community | juleswritescode | @@ -0,0 +1,36 @@
+/**
+ * Gets the path of the Biome binary for the current platform | ```suggestion
* Gets the path of the PGLT binary for the current platform
``` |
postgres_lsp | github_2023 | typescript | 240 | supabase-community | juleswritescode | @@ -0,0 +1,47 @@
+import { spawn } from "node:child_process";
+import { type Socket, connect } from "node:net";
+
+function getSocket(command: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const process = spawn(command, ["__print_socket"], {
+ stdio: "pipe",
+ });
+
+ process.on("error", reject);
+
+ let pipeName = "";
+ process.stdout.on("data", (data) => {
+ pipeName += data.toString("utf-8");
+ });
+
+ process.on("exit", (code) => {
+ if (code === 0) {
+ resolve(pipeName.trimEnd());
+ } else {
+ reject(
+ new Error(
+ `Command '${command} __print_socket' exited with code ${code}`,
+ ),
+ );
+ }
+ });
+ });
+}
+
+/**
+ * Ensure the Biome daemon server is running and create a Socket connected to the RPC channel | ```suggestion
* Ensure the PGLT daemon server is running and create a Socket connected to the RPC channel
``` |
postgres_lsp | github_2023 | typescript | 240 | supabase-community | juleswritescode | @@ -0,0 +1,47 @@
+import { spawn } from "node:child_process";
+import { type Socket, connect } from "node:net";
+
+function getSocket(command: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const process = spawn(command, ["__print_socket"], {
+ stdio: "pipe",
+ });
+
+ process.on("error", reject);
+
+ let pipeName = "";
+ process.stdout.on("data", (data) => {
+ pipeName += data.toString("utf-8");
+ });
+
+ process.on("exit", (code) => {
+ if (code === 0) {
+ resolve(pipeName.trimEnd());
+ } else {
+ reject(
+ new Error(
+ `Command '${command} __print_socket' exited with code ${code}`,
+ ),
+ );
+ }
+ });
+ });
+}
+
+/**
+ * Ensure the Biome daemon server is running and create a Socket connected to the RPC channel
+ *
+ * @param command Path to the Biome daemon binary | ```suggestion
* @param command Path to the PGLT daemon binary
``` |
postgres_lsp | github_2023 | typescript | 240 | supabase-community | juleswritescode | @@ -0,0 +1,453 @@
+// Generated file, do not edit by hand, see `xtask/codegen` | epic |
postgres_lsp | github_2023 | others | 239 | supabase-community | juleswritescode | @@ -168,7 +169,20 @@ pub fn create_config(
}
})?;
- let contents = toml::ser::to_string_pretty(&configuration)
+ // we now check if biome is installed inside `node_modules` and if so, we use the schema from there | 
|
postgres_lsp | github_2023 | others | 239 | supabase-community | juleswritescode | @@ -168,7 +169,20 @@ pub fn create_config(
}
})?;
- let contents = toml::ser::to_string_pretty(&configuration)
+ // we now check if biome is installed inside `node_modules` and if so, we use the schema from there
+ if VERSION == "0.0.0" {
+ let schema_path = Path::new("./node_modules/@pglt/pglt/schema.json"); | den Part verstehe ich nicht so ganz, die früheste Version auf NPM wird ja >0.1.0 sein? |
postgres_lsp | github_2023 | others | 239 | supabase-community | juleswritescode | @@ -186,3 +200,68 @@ pub fn to_analyser_rules(settings: &Settings) -> AnalyserRules {
}
analyser_rules
}
+
+/// Takes a string of jsonc content and returns a comment free version
+/// which should parse fine as regular json.
+/// Nested block comments are supported.
+pub fn strip_jsonc_comments(jsonc_input: &str) -> String { | wollen wir hierfür noch ein paar unit tests hinzufügen? |
postgres_lsp | github_2023 | others | 237 | supabase-community | juleswritescode | @@ -142,6 +146,21 @@ impl Parser {
}
}
+ /// Look ahead to the next relevant token *after the next token* | Der Kommentar innerhalb der \*\* ist n bisschen confusing, es ist zwar under the hood `next_pos + 1` aber für clients der API im Prinzip `current + 1`, oder? So liest es sich unten jedenfalls bei dem Ordinality check |
postgres_lsp | github_2023 | others | 216 | supabase-community | juleswritescode | @@ -0,0 +1,13 @@
+-- test
+select id, name, test1231234123, unknown from co;
+
+-- in between two statements
+
+select 14433313331333 -- after a statement | sanity check: `;` fehlt? |
postgres_lsp | github_2023 | others | 216 | supabase-community | juleswritescode | @@ -55,8 +55,8 @@ jobs:
- name: Abort
if: steps.validate-release.outputs.has-release != 'true'
run: |
- {
- echo "Tag ${{ github.event.inputs.release_tag }} not found."
+ {
+ echo "Tag ${{ github.event.inputs.release-tag }} not found." | \*angry old man noises\* |
postgres_lsp | github_2023 | others | 216 | supabase-community | juleswritescode | @@ -61,8 +61,18 @@ pub static WHITESPACE_TOKENS: &[SyntaxKind] = &[
SyntaxKind::SqlComment,
];
-static PATTERN_LEXER: LazyLock<Regex> =
- LazyLock::new(|| Regex::new(r"(?P<whitespace> +)|(?P<newline>\r?\n+)|(?P<tab>\t+)").unwrap());
+static PATTERN_LEXER: LazyLock<Regex> = LazyLock::new(|| {
+ #[cfg(windows)]
+ {
+ // On Windows, treat \r\n as a single newline token
+ Regex::new(r"(?P<whitespace> +)|(?P<newline>\r\n|\n+)|(?P<tab>\t+)").unwrap() | machste das noch in dem PR? |
postgres_lsp | github_2023 | others | 219 | supabase-community | juleswritescode | @@ -0,0 +1,63 @@
+use pglt_diagnostics::{Diagnostic, MessageAndDescription};
+use text_size::TextRange;
+
+/// A specialized diagnostic for scan errors.
+///
+/// Scan diagnostics are always **fatal errors**.
+#[derive(Clone, Debug, Diagnostic, PartialEq)]
+#[diagnostic(category = "syntax", severity = Fatal)]
+pub struct ScanError {
+ /// The location where the error is occurred
+ #[location(span)]
+ span: Option<TextRange>,
+ #[message]
+ #[description]
+ pub message: MessageAndDescription,
+}
+
+impl ScanError {
+ pub fn from_pg_query_err(err: pg_query::Error, input: &str) -> Vec<Self> {
+ let err_msg = err.to_string();
+ let re = regex::Regex::new(r#"at or near "(.*?)""#).unwrap();
+ let mut diagnostics = Vec::new();
+
+ for captures in re.captures_iter(&err_msg) {
+ if let Some(matched) = captures.get(1) {
+ let search_term = matched.as_str();
+ for (idx, _) in input.match_indices(search_term) { | what happens if we have multiple matches in an input? Is that possible? |
postgres_lsp | github_2023 | others | 219 | supabase-community | juleswritescode | @@ -0,0 +1,63 @@
+use pglt_diagnostics::{Diagnostic, MessageAndDescription};
+use text_size::TextRange;
+
+/// A specialized diagnostic for scan errors.
+///
+/// Scan diagnostics are always **fatal errors**.
+#[derive(Clone, Debug, Diagnostic, PartialEq)]
+#[diagnostic(category = "syntax", severity = Fatal)]
+pub struct ScanError {
+ /// The location where the error is occurred
+ #[location(span)]
+ span: Option<TextRange>,
+ #[message]
+ #[description]
+ pub message: MessageAndDescription,
+}
+
+impl ScanError {
+ pub fn from_pg_query_err(err: pg_query::Error, input: &str) -> Vec<Self> {
+ let err_msg = err.to_string();
+ let re = regex::Regex::new(r#"at or near "(.*?)""#).unwrap();
+ let mut diagnostics = Vec::new();
+
+ for captures in re.captures_iter(&err_msg) {
+ if let Some(matched) = captures.get(1) {
+ let search_term = matched.as_str();
+ for (idx, _) in input.match_indices(search_term) {
+ let from = idx;
+ let to = from + search_term.len();
+ diagnostics.push(ScanError {
+ span: Some(TextRange::new(
+ from.try_into().unwrap(),
+ to.try_into().unwrap(),
+ )),
+ message: MessageAndDescription::from(err_msg.clone()),
+ });
+ }
+ }
+ }
+
+ if diagnostics.is_empty() {
+ diagnostics.push(ScanError {
+ span: None,
+ message: MessageAndDescription::from(err_msg),
+ });
+ }
+
+ diagnostics
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::lex;
+
+ #[test]
+ fn finds_all_occurrences() {
+ let input =
+ "select 1443ddwwd33djwdkjw13331333333333; select 1443ddwwd33djwdkjw13331333333333;"; | the diagnostics should have distinct ranges, should we assert that as well? |
postgres_lsp | github_2023 | others | 219 | supabase-community | juleswritescode | @@ -235,7 +259,22 @@ impl Document {
.get(usize::from(affected_range.start())..usize::from(affected_range.end()))
.unwrap();
- let new_ranges = pglt_statement_splitter::split(changed_content).ranges;
+ let (new_ranges, diags) =
+ document::split_with_diagnostics(changed_content, Some(affected_range.start()));
+
+ self.diagnostics = diags;
+
+ if self
+ .diagnostics
+ .iter()
+ .any(|d| d.severity() == pglt_diagnostics::Severity::Fatal) | hard to see in the github diff, but is `self` not a `Document` and we can check the fatal_error helper? |
postgres_lsp | github_2023 | others | 219 | supabase-community | juleswritescode | @@ -289,7 +328,22 @@ impl Document {
.get(usize::from(full_affected_range.start())..usize::from(full_affected_range.end()))
.unwrap();
- let new_ranges = pglt_statement_splitter::split(changed_content).ranges;
+ let (new_ranges, diags) =
+ document::split_with_diagnostics(changed_content, Some(full_affected_range.start()));
+
+ self.diagnostics = diags;
+
+ if self
+ .diagnostics
+ .iter()
+ .any(|d| d.severity() == pglt_diagnostics::Severity::Fatal) | hard to see in the github diff, but is `self` not a `Document` and we can check the fatal_error helper? |
postgres_lsp | github_2023 | others | 219 | supabase-community | juleswritescode | @@ -69,37 +75,55 @@ impl Document {
changes
}
- /// Applies a full change to the document and returns the affected statements
- fn apply_full_change(&mut self, text: &str) -> Vec<StatementChange> {
+ /// Helper method to drain all positions and return them as deleted statements
+ fn drain_positions(&mut self) -> Vec<StatementChange> {
+ self.positions
+ .drain(..)
+ .map(|(id, _)| {
+ StatementChange::Deleted(Statement {
+ id,
+ path: self.path.clone(),
+ })
+ })
+ .collect()
+ }
+
+ /// Applies a change to the document and returns the affected statements
+ ///
+ /// Will always assume its a full change and reparse the whole document
+ fn apply_full_change(&mut self, change: &ChangeParams) -> Vec<StatementChange> {
let mut changes = Vec::new();
- changes.extend(self.positions.drain(..).map(|(id, _)| {
- StatementChange::Deleted(Statement {
- id,
- path: self.path.clone(),
- })
- }));
+ changes.extend(self.drain_positions());
- self.content = text.to_string();
+ self.content = change.apply_to_text(&self.content);
- changes.extend(
- pglt_statement_splitter::split(&self.content)
- .ranges
- .into_iter()
- .map(|range| {
- let id = self.id_generator.next();
- let text = self.content[range].to_string();
- self.positions.push((id, range));
+ let (ranges, diagnostics) = document::split_with_diagnostics(&self.content, None);
- StatementChange::Added(AddedStatement {
- stmt: Statement {
- path: self.path.clone(),
- id,
- },
- text,
- })
- }),
- );
+ self.diagnostics = diagnostics;
+
+ // Do not add any statements if there is a fatal error
+ if self
+ .diagnostics
+ .iter()
+ .any(|d| d.severity() == pglt_diagnostics::Severity::Fatal) | hard to see in the github diff, but is `self` not a `Document` and we can check the fatal_error helper? |
postgres_lsp | github_2023 | others | 219 | supabase-community | juleswritescode | @@ -289,7 +328,22 @@ impl Document {
.get(usize::from(full_affected_range.start())..usize::from(full_affected_range.end()))
.unwrap();
- let new_ranges = pglt_statement_splitter::split(changed_content).ranges;
+ let (new_ranges, diags) =
+ document::split_with_diagnostics(changed_content, Some(full_affected_range.start()));
+
+ self.diagnostics = diags;
+
+ if self
+ .diagnostics
+ .iter()
+ .any(|d| d.severity() == pglt_diagnostics::Severity::Fatal)
+ {
+ // cleanup all positions if there is a fatal error
+ changed.extend(self.drain_positions());
+ // still process text change
+ self.content = new_content;
+ return changed; | nit: duplicate logic |
postgres_lsp | github_2023 | others | 215 | supabase-community | psteinroe | @@ -0,0 +1,36 @@
+{
+ "name": "pglt",
+ "version": "0.1.0",
+ "bin": {
+ "pglt": "bin/pglt"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/supabase/postgres_lsp.git",
+ "directory": "packages/@pglt/pglt"
+ },
+ "author": "Philipp Steinrötter",
+ "contributors": [
+ {
+ "name": "Julian Domke", | Can you change this to supabase community and just list me as a contributor? |
postgres_lsp | github_2023 | others | 214 | supabase-community | juleswritescode | @@ -0,0 +1,341 @@
+use anyhow::bail;
+use anyhow::Context;
+use anyhow::Error;
+use anyhow::Result;
+use futures::channel::mpsc::{channel, Sender};
+use futures::Sink;
+use futures::SinkExt;
+use futures::Stream;
+use futures::StreamExt;
+use pglt_lsp::LSPServer;
+use pglt_lsp::ServerFactory;
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use serde_json::{from_value, to_value};
+use std::any::type_name;
+use std::fmt::Display;
+use std::time::Duration;
+use tower::timeout::Timeout;
+use tower::{Service, ServiceExt};
+use tower_lsp::jsonrpc;
+use tower_lsp::jsonrpc::Response;
+use tower_lsp::lsp_types as lsp;
+use tower_lsp::lsp_types::DidCloseTextDocumentParams;
+use tower_lsp::lsp_types::DidOpenTextDocumentParams;
+use tower_lsp::lsp_types::InitializeResult;
+use tower_lsp::lsp_types::InitializedParams;
+use tower_lsp::lsp_types::PublishDiagnosticsParams;
+use tower_lsp::lsp_types::TextDocumentContentChangeEvent;
+use tower_lsp::lsp_types::TextDocumentIdentifier;
+use tower_lsp::lsp_types::TextDocumentItem;
+use tower_lsp::lsp_types::VersionedTextDocumentIdentifier; | the use statements look a bit odd? something wrong with your nvim config? |
postgres_lsp | github_2023 | others | 214 | supabase-community | juleswritescode | @@ -0,0 +1,341 @@
+use anyhow::bail;
+use anyhow::Context;
+use anyhow::Error;
+use anyhow::Result;
+use futures::channel::mpsc::{channel, Sender};
+use futures::Sink;
+use futures::SinkExt;
+use futures::Stream;
+use futures::StreamExt;
+use pglt_lsp::LSPServer;
+use pglt_lsp::ServerFactory;
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use serde_json::{from_value, to_value};
+use std::any::type_name;
+use std::fmt::Display;
+use std::time::Duration;
+use tower::timeout::Timeout;
+use tower::{Service, ServiceExt};
+use tower_lsp::jsonrpc;
+use tower_lsp::jsonrpc::Response;
+use tower_lsp::lsp_types as lsp;
+use tower_lsp::lsp_types::DidCloseTextDocumentParams;
+use tower_lsp::lsp_types::DidOpenTextDocumentParams;
+use tower_lsp::lsp_types::InitializeResult;
+use tower_lsp::lsp_types::InitializedParams;
+use tower_lsp::lsp_types::PublishDiagnosticsParams;
+use tower_lsp::lsp_types::TextDocumentContentChangeEvent;
+use tower_lsp::lsp_types::TextDocumentIdentifier;
+use tower_lsp::lsp_types::TextDocumentItem;
+use tower_lsp::lsp_types::VersionedTextDocumentIdentifier;
+use tower_lsp::lsp_types::{ClientCapabilities, Url};
+use tower_lsp::lsp_types::{DidChangeConfigurationParams, DidChangeTextDocumentParams};
+use tower_lsp::LspService;
+use tower_lsp::{jsonrpc::Request, lsp_types::InitializeParams};
+
+/// Statically build an [Url] instance that points to the file at `$path`
+/// within the workspace. The filesystem path contained in the return URI is
+/// guaranteed to be a valid path for the underlying operating system, but
+/// doesn't have to refer to an existing file on the host machine.
+macro_rules! url {
+ ($path:literal) => {
+ if cfg!(windows) {
+ lsp::Url::parse(concat!("file:///z%3A/workspace/", $path)).unwrap()
+ } else {
+ lsp::Url::parse(concat!("file:///workspace/", $path)).unwrap()
+ }
+ };
+} | pretty cool |
postgres_lsp | github_2023 | others | 214 | supabase-community | juleswritescode | @@ -0,0 +1,341 @@
+use anyhow::bail;
+use anyhow::Context;
+use anyhow::Error;
+use anyhow::Result;
+use futures::channel::mpsc::{channel, Sender};
+use futures::Sink;
+use futures::SinkExt;
+use futures::Stream;
+use futures::StreamExt;
+use pglt_lsp::LSPServer;
+use pglt_lsp::ServerFactory;
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use serde_json::{from_value, to_value};
+use std::any::type_name;
+use std::fmt::Display;
+use std::time::Duration;
+use tower::timeout::Timeout;
+use tower::{Service, ServiceExt};
+use tower_lsp::jsonrpc;
+use tower_lsp::jsonrpc::Response;
+use tower_lsp::lsp_types as lsp;
+use tower_lsp::lsp_types::DidCloseTextDocumentParams;
+use tower_lsp::lsp_types::DidOpenTextDocumentParams;
+use tower_lsp::lsp_types::InitializeResult;
+use tower_lsp::lsp_types::InitializedParams;
+use tower_lsp::lsp_types::PublishDiagnosticsParams;
+use tower_lsp::lsp_types::TextDocumentContentChangeEvent;
+use tower_lsp::lsp_types::TextDocumentIdentifier;
+use tower_lsp::lsp_types::TextDocumentItem;
+use tower_lsp::lsp_types::VersionedTextDocumentIdentifier;
+use tower_lsp::lsp_types::{ClientCapabilities, Url};
+use tower_lsp::lsp_types::{DidChangeConfigurationParams, DidChangeTextDocumentParams};
+use tower_lsp::LspService;
+use tower_lsp::{jsonrpc::Request, lsp_types::InitializeParams};
+
+/// Statically build an [Url] instance that points to the file at `$path`
+/// within the workspace. The filesystem path contained in the return URI is
+/// guaranteed to be a valid path for the underlying operating system, but
+/// doesn't have to refer to an existing file on the host machine.
+macro_rules! url {
+ ($path:literal) => {
+ if cfg!(windows) {
+ lsp::Url::parse(concat!("file:///z%3A/workspace/", $path)).unwrap()
+ } else {
+ lsp::Url::parse(concat!("file:///workspace/", $path)).unwrap()
+ }
+ };
+}
+
+struct Server {
+ service: Timeout<LspService<LSPServer>>,
+}
+
+impl Server {
+ fn new(service: LspService<LSPServer>) -> Self {
+ Self {
+ service: Timeout::new(service, Duration::from_secs(1)),
+ }
+ }
+
+ async fn notify<P>(&mut self, method: &'static str, params: P) -> Result<()>
+ where
+ P: Serialize,
+ {
+ self.service
+ .ready()
+ .await
+ .map_err(Error::msg)
+ .context("ready() returned an error")?
+ .call(
+ Request::build(method)
+ .params(to_value(¶ms).context("failed to serialize params")?)
+ .finish(),
+ )
+ .await
+ .map_err(Error::msg)
+ .context("call() returned an error")
+ .and_then(|res| {
+ if let Some(res) = res {
+ bail!("shutdown returned {:?}", res) | Are we shutting down here? |
postgres_lsp | github_2023 | others | 214 | supabase-community | juleswritescode | @@ -0,0 +1,341 @@
+use anyhow::bail;
+use anyhow::Context;
+use anyhow::Error;
+use anyhow::Result;
+use futures::channel::mpsc::{channel, Sender};
+use futures::Sink;
+use futures::SinkExt;
+use futures::Stream;
+use futures::StreamExt;
+use pglt_lsp::LSPServer;
+use pglt_lsp::ServerFactory;
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use serde_json::{from_value, to_value};
+use std::any::type_name;
+use std::fmt::Display;
+use std::time::Duration;
+use tower::timeout::Timeout;
+use tower::{Service, ServiceExt};
+use tower_lsp::jsonrpc;
+use tower_lsp::jsonrpc::Response;
+use tower_lsp::lsp_types as lsp;
+use tower_lsp::lsp_types::DidCloseTextDocumentParams;
+use tower_lsp::lsp_types::DidOpenTextDocumentParams;
+use tower_lsp::lsp_types::InitializeResult;
+use tower_lsp::lsp_types::InitializedParams;
+use tower_lsp::lsp_types::PublishDiagnosticsParams;
+use tower_lsp::lsp_types::TextDocumentContentChangeEvent;
+use tower_lsp::lsp_types::TextDocumentIdentifier;
+use tower_lsp::lsp_types::TextDocumentItem;
+use tower_lsp::lsp_types::VersionedTextDocumentIdentifier;
+use tower_lsp::lsp_types::{ClientCapabilities, Url};
+use tower_lsp::lsp_types::{DidChangeConfigurationParams, DidChangeTextDocumentParams};
+use tower_lsp::LspService;
+use tower_lsp::{jsonrpc::Request, lsp_types::InitializeParams};
+
+/// Statically build an [Url] instance that points to the file at `$path`
+/// within the workspace. The filesystem path contained in the return URI is
+/// guaranteed to be a valid path for the underlying operating system, but
+/// doesn't have to refer to an existing file on the host machine.
+macro_rules! url {
+ ($path:literal) => {
+ if cfg!(windows) {
+ lsp::Url::parse(concat!("file:///z%3A/workspace/", $path)).unwrap()
+ } else {
+ lsp::Url::parse(concat!("file:///workspace/", $path)).unwrap()
+ }
+ };
+}
+
+struct Server {
+ service: Timeout<LspService<LSPServer>>,
+}
+
+impl Server {
+ fn new(service: LspService<LSPServer>) -> Self {
+ Self {
+ service: Timeout::new(service, Duration::from_secs(1)),
+ }
+ }
+
+ async fn notify<P>(&mut self, method: &'static str, params: P) -> Result<()>
+ where
+ P: Serialize,
+ {
+ self.service
+ .ready()
+ .await
+ .map_err(Error::msg)
+ .context("ready() returned an error")?
+ .call(
+ Request::build(method)
+ .params(to_value(¶ms).context("failed to serialize params")?)
+ .finish(),
+ )
+ .await
+ .map_err(Error::msg)
+ .context("call() returned an error")
+ .and_then(|res| { | Hmm, would it be more flexible to let test callers handle the response themselves? |
postgres_lsp | github_2023 | others | 214 | supabase-community | juleswritescode | @@ -0,0 +1,341 @@
+use anyhow::bail;
+use anyhow::Context;
+use anyhow::Error;
+use anyhow::Result;
+use futures::channel::mpsc::{channel, Sender};
+use futures::Sink;
+use futures::SinkExt;
+use futures::Stream;
+use futures::StreamExt;
+use pglt_lsp::LSPServer;
+use pglt_lsp::ServerFactory;
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use serde_json::{from_value, to_value};
+use std::any::type_name;
+use std::fmt::Display;
+use std::time::Duration;
+use tower::timeout::Timeout;
+use tower::{Service, ServiceExt};
+use tower_lsp::jsonrpc;
+use tower_lsp::jsonrpc::Response;
+use tower_lsp::lsp_types as lsp;
+use tower_lsp::lsp_types::DidCloseTextDocumentParams;
+use tower_lsp::lsp_types::DidOpenTextDocumentParams;
+use tower_lsp::lsp_types::InitializeResult;
+use tower_lsp::lsp_types::InitializedParams;
+use tower_lsp::lsp_types::PublishDiagnosticsParams;
+use tower_lsp::lsp_types::TextDocumentContentChangeEvent;
+use tower_lsp::lsp_types::TextDocumentIdentifier;
+use tower_lsp::lsp_types::TextDocumentItem;
+use tower_lsp::lsp_types::VersionedTextDocumentIdentifier;
+use tower_lsp::lsp_types::{ClientCapabilities, Url};
+use tower_lsp::lsp_types::{DidChangeConfigurationParams, DidChangeTextDocumentParams};
+use tower_lsp::LspService;
+use tower_lsp::{jsonrpc::Request, lsp_types::InitializeParams};
+
+/// Statically build an [Url] instance that points to the file at `$path`
+/// within the workspace. The filesystem path contained in the return URI is
+/// guaranteed to be a valid path for the underlying operating system, but
+/// doesn't have to refer to an existing file on the host machine.
+macro_rules! url {
+ ($path:literal) => {
+ if cfg!(windows) {
+ lsp::Url::parse(concat!("file:///z%3A/workspace/", $path)).unwrap()
+ } else {
+ lsp::Url::parse(concat!("file:///workspace/", $path)).unwrap()
+ }
+ };
+}
+
+struct Server {
+ service: Timeout<LspService<LSPServer>>,
+}
+
+impl Server {
+ fn new(service: LspService<LSPServer>) -> Self {
+ Self {
+ service: Timeout::new(service, Duration::from_secs(1)),
+ }
+ }
+
+ async fn notify<P>(&mut self, method: &'static str, params: P) -> Result<()>
+ where
+ P: Serialize,
+ {
+ self.service
+ .ready()
+ .await
+ .map_err(Error::msg)
+ .context("ready() returned an error")?
+ .call(
+ Request::build(method)
+ .params(to_value(¶ms).context("failed to serialize params")?)
+ .finish(),
+ )
+ .await
+ .map_err(Error::msg)
+ .context("call() returned an error")
+ .and_then(|res| {
+ if let Some(res) = res {
+ bail!("shutdown returned {:?}", res)
+ } else {
+ Ok(())
+ }
+ })
+ }
+
+ async fn request<P, R>(
+ &mut self,
+ method: &'static str,
+ id: &'static str,
+ params: P,
+ ) -> Result<Option<R>>
+ where
+ P: Serialize,
+ R: DeserializeOwned,
+ {
+ self.service
+ .ready()
+ .await
+ .map_err(Error::msg)
+ .context("ready() returned an error")?
+ .call(
+ Request::build(method)
+ .id(id)
+ .params(to_value(¶ms).context("failed to serialize params")?)
+ .finish(),
+ )
+ .await
+ .map_err(Error::msg)
+ .context("call() returned an error")?
+ .map(|res| {
+ let (_, body) = res.into_parts();
+
+ let body =
+ body.with_context(|| format!("response to {method:?} contained an error"))?;
+
+ from_value(body.clone()).with_context(|| {
+ format!(
+ "failed to deserialize type {} from response {body:?}",
+ type_name::<R>()
+ )
+ })
+ })
+ .transpose()
+ }
+
+ /// Basic implementation of the `initialize` request for tests
+ // The `root_path` field is deprecated, but we still need to specify it
+ #[allow(deprecated)]
+ async fn initialize(&mut self) -> Result<()> {
+ let _res: InitializeResult = self
+ .request(
+ "initialize",
+ "_init",
+ InitializeParams {
+ process_id: None,
+ root_path: None,
+ root_uri: Some(url!("")),
+ initialization_options: None,
+ capabilities: ClientCapabilities::default(),
+ trace: None,
+ workspace_folders: None,
+ client_info: None,
+ locale: None,
+ },
+ )
+ .await?
+ .context("initialize returned None")?;
+
+ Ok(())
+ }
+
+ /// Basic implementation of the `initialized` notification for tests
+ async fn initialized(&mut self) -> Result<()> {
+ self.notify("initialized", InitializedParams {}).await
+ }
+
+ /// Basic implementation of the `shutdown` notification for tests
+ async fn shutdown(&mut self) -> Result<()> {
+ self.service
+ .ready()
+ .await
+ .map_err(Error::msg)
+ .context("ready() returned an error")?
+ .call(Request::build("shutdown").finish())
+ .await
+ .map_err(Error::msg)
+ .context("call() returned an error")
+ .and_then(|res| {
+ if let Some(res) = res {
+ bail!("shutdown returned {:?}", res)
+ } else {
+ Ok(())
+ }
+ })
+ }
+
+ async fn open_document(&mut self, text: impl Display) -> Result<()> {
+ self.notify(
+ "textDocument/didOpen",
+ DidOpenTextDocumentParams {
+ text_document: TextDocumentItem {
+ uri: url!("document.js"),
+ language_id: String::from("javascript"),
+ version: 0,
+ text: text.to_string(),
+ },
+ },
+ ) | Just a feeling: I think we need to be careful about what we abstract away and what we force the tests to do themselves.
For methods that are always called like `shutdown`, `initialize` etc. I think it makes sense to provide convenience methods.
But I'm not super about e.g. `open_document` – a bug might slip in because our testing logic contains too much "business logic".
Also, this is javascript 🤣
But yeah, WDYT? I think it's a fine line |
postgres_lsp | github_2023 | others | 208 | supabase-community | psteinroe | @@ -0,0 +1,67 @@
+use pglt_analyse::{context::RuleContext, declare_lint_rule, Rule, RuleDiagnostic, RuleSource};
+use pglt_console::markup;
+
+declare_lint_rule! {
+ /// Adding a new column that is NOT NULL and has no default value to an existing table effectively makes it required.
+ ///
+ /// This will fail immediately upon running for any populated table. Furthermore, old application code that is unaware of this column will fail to INSERT to this table.
+ ///
+ /// Make new columns optional initially by omitting the NOT NULL constraint until all existing data and application code has been updated. Once no NULL values are written to or persisted in the database, set it to NOT NULL.
+ /// Alternatively, if using Postgres version 11 or later, add a DEFAULT value that is not volatile. This allows the column to keep its NOT NULL constraint.
+ ///
+ /// ## Invalid
+ /// alter table test add column count int not null;
+ ///
+ /// ## Valid in Postgres >= 11
+ /// alter table test add column count int not null default 0; | we should pass the current postgres version to the rules! |
postgres_lsp | github_2023 | others | 206 | supabase-community | juleswritescode | @@ -124,7 +124,9 @@ jobs:
token: ${{ secrets.GITHUB_TOKEN }}
body: ${{ steps.create_changelog.outputs.content }}
tag_name: ${{ steps.create_changelog.outputs.version }}
- files: pglt_*
+ files: |
+ pglt_*
+ docs/schemas/latest/schema.json | Nice! Should we also regenerate the schema as part of the release workflow? |
postgres_lsp | github_2023 | others | 204 | supabase-community | juleswritescode | @@ -0,0 +1,464 @@
+use anyhow::{bail, Result};
+use biome_string_case::Case;
+use pglt_analyse::{AnalyserOptions, AnalysisFilter, RuleFilter, RuleMetadata};
+use pglt_analyser::{Analyser, AnalyserConfig};
+use pglt_console::StdDisplay;
+use pglt_diagnostics::{Diagnostic, DiagnosticExt, PrintDiagnostic};
+use pglt_query_ext::diagnostics::SyntaxDiagnostic;
+use pglt_workspace::settings::Settings;
+use pulldown_cmark::{CodeBlockKind, Event, LinkType, Parser, Tag, TagEnd};
+use std::{
+ fmt::Write as _,
+ fs,
+ io::{self, Write as _},
+ path::Path,
+ slice,
+ str::{self, FromStr},
+};
+
+/// Generates the documentation page for each lint rule.
+///
+/// * `docs_dir`: Path to the docs directory.
+pub fn generate_rules_docs(docs_dir: &Path) -> anyhow::Result<()> {
+ let rules_dir = docs_dir.join("rules");
+
+ if rules_dir.exists() {
+ fs::remove_dir_all(&rules_dir)?;
+ }
+ fs::create_dir_all(&rules_dir)?;
+
+ let mut visitor = crate::utils::LintRulesVisitor::default();
+ pglt_analyser::visit_registry(&mut visitor);
+
+ let crate::utils::LintRulesVisitor { groups } = visitor;
+
+ for (group, rules) in groups {
+ for (rule, metadata) in rules {
+ let content = generate_rule_doc(group, rule, metadata)?;
+ let dashed_rule = Case::Kebab.convert(rule);
+ fs::write(rules_dir.join(format!("{}.md", dashed_rule)), content)?;
+ }
+ }
+
+ Ok(())
+}
+
+fn generate_rule_doc(
+ group: &'static str,
+ rule: &'static str,
+ meta: RuleMetadata,
+) -> Result<String> {
+ let mut content = Vec::new();
+
+ writeln!(content, "# {rule}")?;
+
+ writeln!(
+ content,
+ "**Diagnostic Category: `lint/{}/{}`**",
+ group, rule
+ )?;
+
+ let is_recommended = meta.recommended;
+
+ // add deprecation notice
+ if let Some(reason) = &meta.deprecated {
+ writeln!(content, "> [!WARNING]")?;
+ writeln!(content, "> This rule is deprecated and will be removed in the next major release.\n**Reason**: {reason}")?;
+ }
+
+ writeln!(content)?;
+ writeln!(content, "**Since**: `v{}`", meta.version)?;
+ writeln!(content)?;
+
+ // add recommended notice
+ if is_recommended {
+ writeln!(content, "> [!NOTE]")?;
+ writeln!(
+ content,
+ "> This rule is recommended. A diagnostic error will appear when linting your code."
+ )?;
+ }
+
+ writeln!(content)?;
+
+ // add source information
+ if !meta.sources.is_empty() {
+ writeln!(content, "**Sources**: ")?;
+
+ for source in meta.sources {
+ let rule_name = source.to_namespaced_rule_name();
+ let source_rule_url = source.to_rule_url();
+ write!(content, "- Inspired from: ")?;
+ writeln!(
+ content,
+ "<a href=\"{source_rule_url}\" target=\"_blank\"><code>{rule_name}</code></a>"
+ )?;
+ }
+ writeln!(content)?;
+ }
+
+ write_documentation(group, rule, meta.docs, &mut content)?; | I just realized that the `declare_lint_rule` macro will use doc comment and attach it as a `.doc` property. I'm impressed 🤯 |
postgres_lsp | github_2023 | others | 204 | supabase-community | juleswritescode | @@ -0,0 +1,464 @@
+use anyhow::{bail, Result};
+use biome_string_case::Case;
+use pglt_analyse::{AnalyserOptions, AnalysisFilter, RuleFilter, RuleMetadata};
+use pglt_analyser::{Analyser, AnalyserConfig};
+use pglt_console::StdDisplay;
+use pglt_diagnostics::{Diagnostic, DiagnosticExt, PrintDiagnostic};
+use pglt_query_ext::diagnostics::SyntaxDiagnostic;
+use pglt_workspace::settings::Settings;
+use pulldown_cmark::{CodeBlockKind, Event, LinkType, Parser, Tag, TagEnd};
+use std::{
+ fmt::Write as _,
+ fs,
+ io::{self, Write as _},
+ path::Path,
+ slice,
+ str::{self, FromStr},
+};
+
+/// Generates the documentation page for each lint rule.
+///
+/// * `docs_dir`: Path to the docs directory.
+pub fn generate_rules_docs(docs_dir: &Path) -> anyhow::Result<()> {
+ let rules_dir = docs_dir.join("rules");
+
+ if rules_dir.exists() {
+ fs::remove_dir_all(&rules_dir)?;
+ }
+ fs::create_dir_all(&rules_dir)?;
+
+ let mut visitor = crate::utils::LintRulesVisitor::default();
+ pglt_analyser::visit_registry(&mut visitor);
+
+ let crate::utils::LintRulesVisitor { groups } = visitor;
+
+ for (group, rules) in groups {
+ for (rule, metadata) in rules {
+ let content = generate_rule_doc(group, rule, metadata)?;
+ let dashed_rule = Case::Kebab.convert(rule);
+ fs::write(rules_dir.join(format!("{}.md", dashed_rule)), content)?;
+ }
+ }
+
+ Ok(())
+}
+
+fn generate_rule_doc(
+ group: &'static str,
+ rule: &'static str,
+ meta: RuleMetadata,
+) -> Result<String> {
+ let mut content = Vec::new();
+
+ writeln!(content, "# {rule}")?;
+
+ writeln!(
+ content,
+ "**Diagnostic Category: `lint/{}/{}`**",
+ group, rule
+ )?;
+
+ let is_recommended = meta.recommended;
+
+ // add deprecation notice
+ if let Some(reason) = &meta.deprecated {
+ writeln!(content, "> [!WARNING]")?;
+ writeln!(content, "> This rule is deprecated and will be removed in the next major release.\n**Reason**: {reason}")?;
+ }
+
+ writeln!(content)?;
+ writeln!(content, "**Since**: `v{}`", meta.version)?;
+ writeln!(content)?;
+
+ // add recommended notice
+ if is_recommended {
+ writeln!(content, "> [!NOTE]")?;
+ writeln!(
+ content,
+ "> This rule is recommended. A diagnostic error will appear when linting your code."
+ )?;
+ }
+
+ writeln!(content)?;
+
+ // add source information
+ if !meta.sources.is_empty() {
+ writeln!(content, "**Sources**: ")?;
+
+ for source in meta.sources {
+ let rule_name = source.to_namespaced_rule_name();
+ let source_rule_url = source.to_rule_url();
+ write!(content, "- Inspired from: ")?;
+ writeln!(
+ content,
+ "<a href=\"{source_rule_url}\" target=\"_blank\"><code>{rule_name}</code></a>"
+ )?;
+ }
+ writeln!(content)?;
+ }
+
+ write_documentation(group, rule, meta.docs, &mut content)?;
+
+ write_how_to_configure(group, rule, &mut content)?;
+
+ Ok(String::from_utf8(content)?)
+}
+
+fn write_how_to_configure(
+ group: &'static str,
+ rule: &'static str,
+ content: &mut Vec<u8>,
+) -> io::Result<()> {
+ writeln!(content, "## How to configure")?;
+ let toml = format!(
+ r#"[linter.rules.{group}]
+{rule} = "error"
+"#
+ );
+
+ writeln!(content, "```toml title=\"pglt.toml\"")?;
+ writeln!(content, "{}", toml)?;
+ writeln!(content, "```")?;
+
+ Ok(())
+}
+
+/// Parse the documentation fragment for a lint rule (in markdown) and generates
+/// the content for the corresponding documentation page
+fn write_documentation(
+ group: &'static str,
+ rule: &'static str,
+ docs: &'static str,
+ content: &mut Vec<u8>,
+) -> Result<()> {
+ writeln!(content, "## Description")?;
+
+ let parser = Parser::new(docs);
+
+ // Tracks the content of the current code block if it's using a
+ // language supported for analysis
+ let mut language = None;
+ let mut list_order = None;
+ let mut list_indentation = 0;
+
+ // Tracks the type and metadata of the link
+ let mut start_link_tag: Option<Tag> = None;
+
+ for event in parser {
+ match event {
+ // CodeBlock-specific handling
+ Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(meta))) => {
+ // Track the content of code blocks to pass them through the analyzer
+ let test = CodeBlockTest::from_str(meta.as_ref())?;
+
+ // Erase the lintdoc-specific attributes in the output by
+ // re-generating the language ID from the source type
+ write!(content, "```{}", &test.tag)?;
+ writeln!(content)?;
+
+ language = Some((test, String::new()));
+ }
+
+ Event::End(TagEnd::CodeBlock) => {
+ writeln!(content, "```")?;
+ writeln!(content)?;
+
+ if let Some((test, block)) = language.take() {
+ if test.expect_diagnostic {
+ writeln!(content, "```sh")?;
+ }
+
+ print_diagnostics(group, rule, &test, &block, content)?;
+
+ if test.expect_diagnostic {
+ writeln!(content, "```")?;
+ writeln!(content)?;
+ }
+ }
+ }
+
+ Event::Text(text) => {
+ let mut hide_line = false;
+
+ if let Some((test, block)) = &mut language {
+ if let Some(inner_text) = text.strip_prefix("# ") {
+ // Lines prefixed with "# " are hidden from the public documentation
+ write!(block, "{inner_text}")?;
+ hide_line = true;
+ test.hidden_lines.push(test.line_count);
+ } else {
+ write!(block, "{text}")?;
+ }
+ test.line_count += 1;
+ }
+
+ if hide_line {
+ // Line should not be emitted into the output
+ } else if matches!(text.as_ref(), "`" | "*" | "_") {
+ write!(content, "\\{text}")?;
+ } else {
+ write!(content, "{text}")?;
+ }
+ }
+
+ // Other markdown events are emitted as-is
+ Event::Start(Tag::Heading { level, .. }) => {
+ write!(content, "{} ", "#".repeat(level as usize))?;
+ }
+ Event::End(TagEnd::Heading { .. }) => {
+ writeln!(content)?;
+ writeln!(content)?;
+ }
+
+ Event::Start(Tag::Paragraph) => {
+ continue;
+ }
+ Event::End(TagEnd::Paragraph) => {
+ writeln!(content)?;
+ writeln!(content)?;
+ }
+
+ Event::Code(text) => {
+ write!(content, "`{text}`")?;
+ }
+ Event::Start(ref link_tag @ Tag::Link { link_type, .. }) => {
+ start_link_tag = Some(link_tag.clone());
+ match link_type {
+ LinkType::Autolink => {
+ write!(content, "<")?;
+ }
+ LinkType::Inline | LinkType::Reference | LinkType::Shortcut => {
+ write!(content, "[")?;
+ }
+ _ => {
+ panic!("unimplemented link type")
+ }
+ }
+ }
+ Event::End(TagEnd::Link) => {
+ if let Some(Tag::Link {
+ link_type,
+ dest_url,
+ title,
+ ..
+ }) = start_link_tag
+ {
+ match link_type {
+ LinkType::Autolink => {
+ write!(content, ">")?;
+ }
+ LinkType::Inline | LinkType::Reference | LinkType::Shortcut => {
+ write!(content, "]({dest_url}")?;
+ if !title.is_empty() {
+ write!(content, " \"{title}\"")?;
+ }
+ write!(content, ")")?;
+ }
+ _ => {
+ panic!("unimplemented link type")
+ }
+ }
+ start_link_tag = None;
+ } else {
+ panic!("missing start link tag");
+ }
+ }
+
+ Event::SoftBreak => {
+ writeln!(content)?;
+ }
+
+ Event::HardBreak => {
+ writeln!(content, "<br />")?;
+ }
+
+ Event::Start(Tag::List(num)) => {
+ list_indentation += 1;
+ if let Some(num) = num {
+ list_order = Some(num);
+ }
+ if list_indentation > 1 {
+ writeln!(content)?;
+ }
+ }
+
+ Event::End(TagEnd::List(_)) => {
+ list_order = None;
+ list_indentation -= 1;
+ writeln!(content)?;
+ }
+ Event::Start(Tag::Item) => {
+ write!(content, "{}", " ".repeat(list_indentation - 1))?;
+ if let Some(num) = list_order {
+ write!(content, "{num}. ")?;
+ } else {
+ write!(content, "- ")?;
+ }
+ }
+
+ Event::End(TagEnd::Item) => {
+ list_order = list_order.map(|item| item + 1);
+ writeln!(content)?;
+ }
+
+ Event::Start(Tag::Strong) => {
+ write!(content, "**")?;
+ }
+
+ Event::End(TagEnd::Strong) => {
+ write!(content, "**")?;
+ }
+
+ Event::Start(Tag::Emphasis) => {
+ write!(content, "_")?;
+ }
+
+ Event::End(TagEnd::Emphasis) => {
+ write!(content, "_")?;
+ }
+
+ Event::Start(Tag::Strikethrough) => {
+ write!(content, "~")?;
+ }
+
+ Event::End(TagEnd::Strikethrough) => {
+ write!(content, "~")?;
+ }
+
+ Event::Start(Tag::BlockQuote(_)) => {
+ write!(content, ">")?;
+ }
+
+ Event::End(TagEnd::BlockQuote(_)) => {
+ writeln!(content)?;
+ }
+
+ _ => {
+ bail!("unimplemented event {event:?}")
+ }
+ }
+ }
+
+ Ok(())
+}
+
+struct CodeBlockTest {
+ /// The language tag of this code block.
+ tag: String,
+
+ /// True if this is an invalid example that should trigger a diagnostic.
+ expect_diagnostic: bool,
+
+ /// Whether to ignore this code block.
+ ignore: bool,
+
+ /// The number of lines in this code block.
+ line_count: u32,
+
+ // The indices of lines that should be hidden from the public documentation.
+ hidden_lines: Vec<u32>,
+}
+
+impl FromStr for CodeBlockTest {
+ type Err = anyhow::Error;
+
+ fn from_str(input: &str) -> Result<Self> {
+ // This is based on the parsing logic for code block languages in `rustdoc`:
+ // https://github.com/rust-lang/rust/blob/6ac8adad1f7d733b5b97d1df4e7f96e73a46db42/src/librustdoc/html/markdown.rs#L873
+ let tokens = input
+ .split([',', ' ', '\t']) | rust is such a great language |
postgres_lsp | github_2023 | others | 204 | supabase-community | juleswritescode | @@ -0,0 +1,55 @@
+use pglt_analyse::{GroupCategory, RegistryVisitor, Rule, RuleCategory, RuleGroup, RuleMetadata};
+use regex::Regex;
+use std::collections::BTreeMap;
+
+pub(crate) fn replace_section(
+ content: &str,
+ section_identifier: &str,
+ replacement: &str,
+) -> String {
+ let pattern = format!(
+ r"(\[//\]: # \(BEGIN {}\)\n)(?s).*?(\n\[//\]: # \(END {}\))",
+ section_identifier, section_identifier
+ );
+ let re = Regex::new(&pattern).unwrap();
+ re.replace_all(content, format!("${{1}}{}${{2}}", replacement))
+ .to_string()
+}
+
+#[derive(Default)]
+pub(crate) struct LintRulesVisitor {
+ /// This is mapped to:
+ /// - group (correctness) -> list of rules
+ /// - list or rules is mapped to
+ /// - rule name -> metadata | ```suggestion
/// group (e.g. "safety") -> <list of rules>
/// where <list of rules> is:
/// <rule name> -> metadata
``` |
postgres_lsp | github_2023 | others | 200 | supabase-community | juleswritescode | @@ -61,28 +61,28 @@ jobs:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
- name: 🛠️ Run Build
- run: cargo build -p pg_cli --release --target ${{ matrix.config.target }}
+ run: cargo build -p pglt_cli --release --target ${{ matrix.config.target }}
# windows is a special snowflake to, it saves binaries as .exe
- name: 👦 Name the Binary
if: matrix.config.os == 'windows-latest'
run: |
mkdir dist
- cp target/${{ matrix.config.target }}/release/pg_cli.exe ./dist/pgcli_${{ matrix.config.target }}
+ cp target/${{ matrix.config.target }}/release/pglt.exe ./dist/pglt_${{ matrix.config.target }} | ```suggestion
cp target/${{ matrix.config.target }}/release/pglt_cli.exe ./dist/pglt_${{ matrix.config.target }}
``` |
postgres_lsp | github_2023 | others | 200 | supabase-community | juleswritescode | @@ -61,28 +61,28 @@ jobs:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
- name: 🛠️ Run Build
- run: cargo build -p pg_cli --release --target ${{ matrix.config.target }}
+ run: cargo build -p pglt_cli --release --target ${{ matrix.config.target }}
# windows is a special snowflake to, it saves binaries as .exe
- name: 👦 Name the Binary
if: matrix.config.os == 'windows-latest'
run: |
mkdir dist
- cp target/${{ matrix.config.target }}/release/pg_cli.exe ./dist/pgcli_${{ matrix.config.target }}
+ cp target/${{ matrix.config.target }}/release/pglt.exe ./dist/pglt_${{ matrix.config.target }}
- name: 👦 Name the Binary
if: matrix.config.os != 'windows-latest'
run: |
mkdir dist
- cp target/${{ matrix.config.target }}/release/pg_cli ./dist/pgcli_${{ matrix.config.target }}
+ cp target/${{ matrix.config.target }}/release/pglt ./dist/pglt_${{ matrix.config.target }} | ```suggestion
cp target/${{ matrix.config.target }}/release/pglt_cli ./dist/pglt_${{ matrix.config.target }}
``` |
postgres_lsp | github_2023 | others | 202 | supabase-community | juleswritescode | @@ -0,0 +1,3 @@
+# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv)
+libpg_query/ | 
|
postgres_lsp | github_2023 | others | 202 | supabase-community | juleswritescode | @@ -2,105 +2,29 @@
# Postgres Language Server
-A Language Server for Postgres. Not SQL with flavors, just Postgres.
+A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.
-> [!WARNING]
-> This is in active development and is only ready for collaborators. But we are getting there! You can find the current roadmap and opportunities to contribute in https://github.com/supabase-community/postgres_lsp/issues/136.
+## Overview
-## Features
+This project provides a toolchain for Postgres development, built on Postgres' own parser `libpg_query` to ensure 100% syntax compatibility. It is built on a Server-Client architecture with a transport-agnostic design. This means all features can be accessed not only through the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), but also through other interfaces like a CLI, HTTP APIs, or a WebAssembly module. The goal is to make all the great Postgres tooling out there as accessible as possible, and to build anything that is missing ourselves.
-The [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) is an open protocol between code editors and servers to provide code intelligence tools such as code completion and syntax highlighting. This project implements such a language server for Postgres, significantly enhancing the developer experience within your favorite editor by adding:
+Currently, the following features are implemented:
+- Autocompletion
+- Syntax Error Highlighting
+- Type-checking (via `EXPLAIN` error insights)
+- Linter, inspired by [Squawk](https://squawkhq.com)
-- Lint
-- Hover
-- Typechecking
-- Syntax Error Diagnostics
-- Inlay Hints
-- Auto-Completion
-- Code actions such as `Execute the statement under the cursor`, or `Execute the current file`
-- Formatter
-- ... and many more
-
-We plan to support all of the above for SQL and PL/pgSQL function bodies too!
-
-## Motivation
-
-Despite the rising popularity of Postgres, support for the PL/pgSQL in IDEs and editors is limited. While there are some _generic_ SQL Language Servers[^1] offering the Postgres syntax as a "flavor" within the parser, they usually fall short due to the ever-evolving and complex syntax of PostgreSQL. There are a few proprietary IDEs[^2] that work well, but the features are only available within the respective IDE.
-
-This Language Server is designed to support Postgres, and only Postgres. The server uses [libpg_query](https://github.com/pganalyze/libpg_query), both as a git submodule for access to its protobuf file and as the [pg_query](https://crates.io/crates/pg_query/5.0.0) rust crate, therefore leveraging the PostgreSQL source to parse the SQL code reliably. Using Postgres within a Language Server might seem unconventional, but it's the only reliable way of parsing all valid PostgreSQL queries. You can find a longer rationale on why This is the Way™ [here](https://pganalyze.com/blog/parse-postgresql-queries-in-ruby). While libpg_query was built to execute SQL, and not to build a language server, any shortcomings have been successfully mitigated in the `parser` crate. You can read the [commented source code](./crates/parser/src/lib.rs) for more details on the inner workings of the parser.
-
-Once the parser is stable, and a robust and scalable data model is implemented, the language server will not only provide basic features such as semantic highlighting, code completion and syntax error diagnostics, but also serve as the user interface for all the great tooling of the Postgres ecosystem.
-
-## Installation
-
-> [!WARNING]
-> This is not ready for production use. Only install this if you want to help with development.
-
-> [!NOTE]
-> Interested in setting up a release process and client extensions for Neovim and VS Code? Please check out https://github.com/supabase-community/postgres_lsp/issues/136!
-
-### Neovim
-
-Add the postgres_lsp executable to your path, and add the following to your config to use it.
-
-```lua
-local util = require 'lspconfig.util'
-local lspconfig = require 'lspconfig'
-
-require('lspconfig.configs').postgres_lsp = {
- default_config = {
- name = 'postgres_lsp',
- cmd = { 'postgres_lsp' },
- filetypes = { 'sql' },
- single_file_support = true,
- root_dir = util.root_pattern 'root-file.txt',
- },
-}
-
-lspconfig.postgres_lsp.setup { force_setup = true }
-```
-
-### Building from source
-
-You'll need _nightly_ Cargo, Node, and npm installed.
-
-Install the `libpg_query` submodule by running:
-
-```sh
-git submodule update --init --recursive
-```
-
-If you are using VS Code, you can install both the server and the client extension by running:
-
-```sh
-cargo xtask install
-```
-
-If you're not using VS Code, you can install the server by running:
-
-```sh
-cargo xtask install --server
-```
-
-The server binary will be installed in `.cargo/bin`. Make sure that `.cargo/bin` is in `$PATH`.
-
-### Github CodeSpaces
-
-You can setup your development environment on [CodeSpaces](https://github.com/features/codespaces).
-
-After your codespace boots up, run the following command in the shell to install Rust:
-
-```shell
-curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
-```
-
-Proceed with the rest of the installation as usual.
+Our current focus is on refining and enhancing these core features while building a robust and easily accessible infrastructure. For future plans and opportunities to contribute, please check out the issues and discussions. Any contributions are welcome!
## Contributors
-- [psteinroe](https://github.com/psteinroe) (Maintainer)
+- [psteinroe](https://github.com/psteinroe)
+- [juleswritescode](https://github.com/juleswritescode)
+
+## Acknowledgements
-## Footnotes
+A big thanks to the following projects, without which this project wouldn't have been possible: | great addition!!! |
postgres_lsp | github_2023 | others | 202 | supabase-community | juleswritescode | @@ -2,105 +2,29 @@
# Postgres Language Server
-A Language Server for Postgres. Not SQL with flavors, just Postgres.
+A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.
-> [!WARNING]
-> This is in active development and is only ready for collaborators. But we are getting there! You can find the current roadmap and opportunities to contribute in https://github.com/supabase-community/postgres_lsp/issues/136.
+## Overview
-## Features
+This project provides a toolchain for Postgres development, built on Postgres' own parser `libpg_query` to ensure 100% syntax compatibility. It is built on a Server-Client architecture with a transport-agnostic design. This means all features can be accessed not only through the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), but also through other interfaces like a CLI, HTTP APIs, or a WebAssembly module. The goal is to make all the great Postgres tooling out there as accessible as possible, and to build anything that is missing ourselves.
-The [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) is an open protocol between code editors and servers to provide code intelligence tools such as code completion and syntax highlighting. This project implements such a language server for Postgres, significantly enhancing the developer experience within your favorite editor by adding:
+Currently, the following features are implemented:
+- Autocompletion
+- Syntax Error Highlighting
+- Type-checking (via `EXPLAIN` error insights)
+- Linter, inspired by [Squawk](https://squawkhq.com)
-- Lint
-- Hover
-- Typechecking
-- Syntax Error Diagnostics
-- Inlay Hints
-- Auto-Completion
-- Code actions such as `Execute the statement under the cursor`, or `Execute the current file`
-- Formatter
-- ... and many more
-
-We plan to support all of the above for SQL and PL/pgSQL function bodies too!
-
-## Motivation
-
-Despite the rising popularity of Postgres, support for the PL/pgSQL in IDEs and editors is limited. While there are some _generic_ SQL Language Servers[^1] offering the Postgres syntax as a "flavor" within the parser, they usually fall short due to the ever-evolving and complex syntax of PostgreSQL. There are a few proprietary IDEs[^2] that work well, but the features are only available within the respective IDE.
-
-This Language Server is designed to support Postgres, and only Postgres. The server uses [libpg_query](https://github.com/pganalyze/libpg_query), both as a git submodule for access to its protobuf file and as the [pg_query](https://crates.io/crates/pg_query/5.0.0) rust crate, therefore leveraging the PostgreSQL source to parse the SQL code reliably. Using Postgres within a Language Server might seem unconventional, but it's the only reliable way of parsing all valid PostgreSQL queries. You can find a longer rationale on why This is the Way™ [here](https://pganalyze.com/blog/parse-postgresql-queries-in-ruby). While libpg_query was built to execute SQL, and not to build a language server, any shortcomings have been successfully mitigated in the `parser` crate. You can read the [commented source code](./crates/parser/src/lib.rs) for more details on the inner workings of the parser.
-
-Once the parser is stable, and a robust and scalable data model is implemented, the language server will not only provide basic features such as semantic highlighting, code completion and syntax error diagnostics, but also serve as the user interface for all the great tooling of the Postgres ecosystem.
-
-## Installation
-
-> [!WARNING]
-> This is not ready for production use. Only install this if you want to help with development.
-
-> [!NOTE]
-> Interested in setting up a release process and client extensions for Neovim and VS Code? Please check out https://github.com/supabase-community/postgres_lsp/issues/136!
-
-### Neovim
-
-Add the postgres_lsp executable to your path, and add the following to your config to use it.
-
-```lua
-local util = require 'lspconfig.util'
-local lspconfig = require 'lspconfig'
-
-require('lspconfig.configs').postgres_lsp = {
- default_config = {
- name = 'postgres_lsp',
- cmd = { 'postgres_lsp' },
- filetypes = { 'sql' },
- single_file_support = true,
- root_dir = util.root_pattern 'root-file.txt',
- },
-}
-
-lspconfig.postgres_lsp.setup { force_setup = true }
-```
-
-### Building from source
-
-You'll need _nightly_ Cargo, Node, and npm installed.
-
-Install the `libpg_query` submodule by running:
-
-```sh
-git submodule update --init --recursive
-```
-
-If you are using VS Code, you can install both the server and the client extension by running:
-
-```sh
-cargo xtask install
-```
-
-If you're not using VS Code, you can install the server by running:
-
-```sh
-cargo xtask install --server
-```
-
-The server binary will be installed in `.cargo/bin`. Make sure that `.cargo/bin` is in `$PATH`.
-
-### Github CodeSpaces
-
-You can setup your development environment on [CodeSpaces](https://github.com/features/codespaces).
-
-After your codespace boots up, run the following command in the shell to install Rust:
-
-```shell
-curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
-```
-
-Proceed with the rest of the installation as usual.
+Our current focus is on refining and enhancing these core features while building a robust and easily accessible infrastructure. For future plans and opportunities to contribute, please check out the issues and discussions. Any contributions are welcome!
## Contributors
-- [psteinroe](https://github.com/psteinroe) (Maintainer)
+- [psteinroe](https://github.com/psteinroe)
+- [juleswritescode](https://github.com/juleswritescode) | 
|
postgres_lsp | github_2023 | others | 194 | supabase-community | psteinroe | @@ -36,15 +40,7 @@ impl Default for DatabaseConfiguration {
username: "postgres".to_string(),
password: "postgres".to_string(),
database: "postgres".to_string(),
+ conn_timeout_secs: Some(10), | 10 seconds is a long time :D usually the connection will happen either within <1s or never, maybe we should set this a bit lower to report issues earlier? |
postgres_lsp | github_2023 | others | 194 | supabase-community | psteinroe | @@ -42,6 +41,30 @@ impl SchemaCache {
})
}
+ fn pool_to_conn_str(pool: &PgPool) -> String { | mhh Connection Str Logic and cache keys on the schema cache feels like a leaking abstraction... why not handling this on the schema cache manager itself? After all, it should manage the schema cache for the workspace and can also be knowledgable of the connection string and handle caching? |
postgres_lsp | github_2023 | others | 194 | supabase-community | psteinroe | @@ -18,6 +18,10 @@ pub struct CliOptions {
#[bpaf(long("use-server"), switch, fallback(false))]
pub use_server: bool,
+ /// Skip over files containing syntax errors instead of emitting an error diagnostic. | Maybe I am misunderstanding, but is this the correct comment? I thought it would simply not connect to the db and still provide everything we can like lint and Syntax diagnostics |
postgres_lsp | github_2023 | others | 194 | supabase-community | psteinroe | @@ -26,6 +26,10 @@ pub struct DatabaseConfiguration {
/// The name of the database.
#[partial(bpaf(long("database")))]
pub database: String,
+
+ /// The connection timeout in seconds.
+ #[partial(bpaf(long("conn_timeout")))]
+ pub conn_timeout_secs: Option<u16>, | Not sure, but maybe we can set the default via bpaf? |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -13,6 +13,10 @@ username = "postgres"
password = "postgres"
database = "postgres"
+[migrations]
+migrations_dir = "migrations"
+after = 20230912094327 | should we remove it? or comment out the properties? |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -0,0 +1,116 @@
+use std::path::Path;
+
+#[derive(Debug)]
+pub(crate) struct Migration {
+ pub(crate) timestamp: u64,
+ pub(crate) name: String,
+}
+
+/// Get the migration associated with a path, if it is a migration file
+pub(crate) fn get_migration(path: &Path, migrations_dir: &Path) -> Option<Migration> {
+ // Check if path is a child of the migration directory
+ let is_child = path
+ .canonicalize()
+ .ok()
+ .and_then(|canonical_child| {
+ migrations_dir
+ .canonicalize()
+ .ok()
+ .map(|canonical_dir| canonical_child.starts_with(&canonical_dir))
+ })
+ .unwrap_or(false);
+
+ if !is_child {
+ return None;
+ }
+
+ // Try Root pattern
+ let root_migration = path
+ .file_name()
+ .and_then(|os_str| os_str.to_str())
+ .and_then(|file_name| {
+ let mut parts = file_name.splitn(2, '_');
+ let timestamp = parts.next()?.parse().ok()?;
+ let name = parts.next()?.to_string();
+ Some(Migration { timestamp, name })
+ });
+
+ if root_migration.is_some() {
+ return root_migration;
+ }
+
+ // Try Subdirectory pattern
+ path.parent()
+ .and_then(|parent| parent.file_name())
+ .and_then(|os_str| os_str.to_str())
+ .and_then(|dir_name| {
+ let mut parts = dir_name.splitn(2, '_');
+ let timestamp = parts.next()?.parse().ok()?;
+ let name = parts.next()?.to_string();
+ Some(Migration { timestamp, name })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+ use std::path::PathBuf;
+ use tempfile::TempDir;
+
+ fn setup() -> TempDir {
+ TempDir::new().expect("Failed to create temp dir")
+ }
+
+ #[test]
+ fn test_get_migration_root_pattern() {
+ let temp_dir = setup();
+ let migrations_dir = temp_dir.path().to_path_buf();
+ let path = migrations_dir.join("1234567890_create_users.sql");
+ fs::write(&path, "").unwrap();
+
+ let migration = get_migration(&path, &migrations_dir);
+
+ assert!(migration.is_some());
+ let migration = migration.unwrap();
+ assert_eq!(migration.timestamp, 1234567890);
+ assert_eq!(migration.name, "create_users.sql");
+ }
+
+ #[test]
+ fn test_get_migration_subdirectory_pattern() {
+ let temp_dir = setup();
+ let migrations_dir = temp_dir.path().to_path_buf();
+ let subdir = migrations_dir.join("1234567890_create_users");
+ fs::create_dir(&subdir).unwrap();
+ let path = subdir.join("up.sql");
+ fs::write(&path, "").unwrap();
+
+ let migration = get_migration(&path, &migrations_dir);
+
+ assert!(migration.is_some());
+ let migration = migration.unwrap();
+ assert_eq!(migration.timestamp, 1234567890);
+ assert_eq!(migration.name, "create_users");
+ }
+
+ #[test]
+ fn test_get_migration_non_migration_file() {
+ let migrations_dir = PathBuf::from("/tmp/migrations");
+ let path = migrations_dir.join("not_a_migration.sql"); | I don't fully understand what we're checking here – are we checking what happens if the .sql file is empty? or if it doesn't match the pattern? |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -0,0 +1,116 @@
+use std::path::Path;
+
+#[derive(Debug)]
+pub(crate) struct Migration {
+ pub(crate) timestamp: u64,
+ pub(crate) name: String,
+}
+
+/// Get the migration associated with a path, if it is a migration file
+pub(crate) fn get_migration(path: &Path, migrations_dir: &Path) -> Option<Migration> {
+ // Check if path is a child of the migration directory
+ let is_child = path
+ .canonicalize()
+ .ok()
+ .and_then(|canonical_child| {
+ migrations_dir
+ .canonicalize()
+ .ok()
+ .map(|canonical_dir| canonical_child.starts_with(&canonical_dir))
+ })
+ .unwrap_or(false);
+
+ if !is_child {
+ return None;
+ }
+
+ // Try Root pattern
+ let root_migration = path
+ .file_name()
+ .and_then(|os_str| os_str.to_str())
+ .and_then(|file_name| {
+ let mut parts = file_name.splitn(2, '_');
+ let timestamp = parts.next()?.parse().ok()?;
+ let name = parts.next()?.to_string();
+ Some(Migration { timestamp, name })
+ });
+
+ if root_migration.is_some() {
+ return root_migration;
+ }
+
+ // Try Subdirectory pattern
+ path.parent()
+ .and_then(|parent| parent.file_name())
+ .and_then(|os_str| os_str.to_str())
+ .and_then(|dir_name| {
+ let mut parts = dir_name.splitn(2, '_');
+ let timestamp = parts.next()?.parse().ok()?;
+ let name = parts.next()?.to_string();
+ Some(Migration { timestamp, name })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+ use std::path::PathBuf;
+ use tempfile::TempDir;
+
+ fn setup() -> TempDir {
+ TempDir::new().expect("Failed to create temp dir") | very cool! |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -0,0 +1,116 @@
+use std::path::Path;
+
+#[derive(Debug)]
+pub(crate) struct Migration {
+ pub(crate) timestamp: u64,
+ pub(crate) name: String,
+}
+
+/// Get the migration associated with a path, if it is a migration file
+pub(crate) fn get_migration(path: &Path, migrations_dir: &Path) -> Option<Migration> {
+ // Check if path is a child of the migration directory
+ let is_child = path
+ .canonicalize()
+ .ok()
+ .and_then(|canonical_child| {
+ migrations_dir
+ .canonicalize()
+ .ok()
+ .map(|canonical_dir| canonical_child.starts_with(&canonical_dir))
+ })
+ .unwrap_or(false);
+
+ if !is_child {
+ return None;
+ }
+
+ // Try Root pattern
+ let root_migration = path
+ .file_name()
+ .and_then(|os_str| os_str.to_str())
+ .and_then(|file_name| {
+ let mut parts = file_name.splitn(2, '_');
+ let timestamp = parts.next()?.parse().ok()?; | I really liked the explanation in the PR description about how popular tools all use similar migrations formats. Should we add a comment somewhere here that we expect a \<TimestampInMs>_\<rest> format? |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -56,7 +62,7 @@ impl CommandRunner for CheckCommandPayload {
}
fn should_write(&self) -> bool {
- self.write || self.fix
+ false | sanity check: did you just change this for debugging? |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -0,0 +1,17 @@
+use biome_deserialize_macros::{Merge, Partial};
+use bpaf::Bpaf;
+use serde::{Deserialize, Serialize};
+
+/// The configuration of the filesystem
+#[derive(Clone, Debug, Deserialize, Eq, Partial, PartialEq, Serialize, Default)]
+#[partial(derive(Bpaf, Clone, Eq, PartialEq, Merge))]
+#[partial(serde(rename_all = "snake_case", default, deny_unknown_fields))]
+pub struct MigrationsConfiguration {
+ /// The directory where the migration files are stored
+ #[partial(bpaf(long("migrations-dir")))]
+ pub migrations_dir: String, | I don't know if we use [bpaf-derive](https://crates.io/crates/bpaf_derive/0.1.0), but if we do, we *could* also parse into a `PathBuf`.
Examples of that were hard to find, so maybe that's not the recommended way – I'm not sure |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -150,13 +157,31 @@ impl WorkspaceServer {
Ok(())
}
+ fn is_ignored_by_migration_config(&self, path: &Path) -> bool {
+ let set = self.settings();
+ set.as_ref()
+ .migrations
+ .as_ref()
+ .and_then(|migration_settings| {
+ tracing::info!("Checking migration settings: {:?}", migration_settings);
+ let ignore_before = migration_settings.after.as_ref()?;
+ tracing::info!("Checking migration settings: {:?}", ignore_before);
+ let migrations_dir = migration_settings.path.as_ref()?;
+ tracing::info!("Checking migration settings: {:?}", migrations_dir);
+ let migration = migration::get_migration(path, migrations_dir)?;
+
+ Some(&migration.timestamp <= ignore_before)
+ })
+ .unwrap_or(false)
+ }
+
/// Check whether a file is ignored in the top-level config `files.ignore`/`files.include`
fn is_ignored(&self, path: &Path) -> bool {
let file_name = path.file_name().and_then(|s| s.to_str());
// Never ignore PGLSP's config file regardless `include`/`ignore`
(file_name != Some(ConfigName::pglsp_toml())) &&
// Apply top-level `include`/`ignore
- (self.is_ignored_by_top_level_config(path))
+ (self.is_ignored_by_top_level_config(path) || self.is_ignored_by_migration_config(path)) | very sweet! |
postgres_lsp | github_2023 | others | 172 | supabase-community | juleswritescode | @@ -150,13 +157,28 @@ impl WorkspaceServer {
Ok(())
}
+ fn is_ignored_by_migration_config(&self, path: &Path) -> bool {
+ let set = self.settings();
+ set.as_ref()
+ .migrations
+ .as_ref()
+ .and_then(|migration_settings| {
+ let ignore_before = migration_settings.after.as_ref()?;
+ let migrations_dir = migration_settings.path.as_ref()?;
+ let migration = migration::get_migration(path, migrations_dir)?;
+
+ Some(&migration.timestamp <= ignore_before)
+ })
+ .unwrap_or(false) | What happens if we pass a migrations_dir but no `after`? Wouldn't the `and_then` return `None`, so the function would always return `false`? |
postgres_lsp | github_2023 | others | 169 | supabase-community | juleswritescode | @@ -0,0 +1,27 @@
+// pub conn: &'a PgPool,
+// pub sql: &'a str,
+// pub ast: &'a pg_query_ext::NodeEnum,
+// pub tree: Option<&'a tree_sitter::Tree>, | ```suggestion
``` |
postgres_lsp | github_2023 | others | 169 | supabase-community | juleswritescode | @@ -25,90 +29,28 @@ pub struct TypeError {
pub constraint: Option<String>,
}
-pub async fn check_sql<'a>(params: TypecheckerParams<'a>) -> Vec<TypeError> {
- let mut errs = vec![];
-
- // prpeared statements work only for select, insert, update, delete, and cte
- if match params.ast {
- pg_query_ext::NodeEnum::SelectStmt(_) => false,
- pg_query_ext::NodeEnum::InsertStmt(_) => false,
- pg_query_ext::NodeEnum::UpdateStmt(_) => false,
- pg_query_ext::NodeEnum::DeleteStmt(_) => false,
- pg_query_ext::NodeEnum::CommonTableExpr(_) => false,
- _ => true,
- } {
- return errs;
+pub async fn check_sql(params: TypecheckParams<'_>) -> Option<TypecheckDiagnostic> {
+ // Check if the AST is not a supported statement type
+ if !matches!(
+ params.ast,
+ pg_query_ext::NodeEnum::SelectStmt(_)
+ | pg_query_ext::NodeEnum::InsertStmt(_)
+ | pg_query_ext::NodeEnum::UpdateStmt(_)
+ | pg_query_ext::NodeEnum::DeleteStmt(_)
+ | pg_query_ext::NodeEnum::CommonTableExpr(_)
+ ) {
+ return None;
}
let res = params.conn.prepare(params.sql).await;
- if res.is_err() {
- if let sqlx::Error::Database(err) = res.as_ref().unwrap_err() {
+ // If there's no error, return an empty vector | ```suggestion
``` |
postgres_lsp | github_2023 | others | 169 | supabase-community | juleswritescode | @@ -336,50 +339,95 @@ impl Workspace for WorkspaceServer {
filter,
});
- let diagnostics: Vec<SDiagnostic> = doc
- .iter_statements_with_range()
- .flat_map(|(stmt, r)| {
- let mut stmt_diagnostics = vec![];
-
- stmt_diagnostics.extend(self.pg_query.get_diagnostics(&stmt));
- let ast = self.pg_query.get_ast(&stmt);
- if let Some(ast) = ast {
- stmt_diagnostics.extend(
- analyser
- .run(AnalyserContext { root: &ast })
- .into_iter()
- .map(SDiagnostic::new)
- .collect::<Vec<_>>(),
- );
- }
-
- stmt_diagnostics
- .into_iter()
- .map(|d| {
- // We do now check if the severity of the diagnostics should be changed.
- // The configuration allows to change the severity of the diagnostics emitted by rules.
- let severity = d
- .category()
- .filter(|category| category.name().starts_with("lint/"))
- .map_or_else(
- || d.severity(),
- |category| {
- settings
- .as_ref()
- .get_severity_from_rule_code(category)
- .unwrap_or(Severity::Warning)
- },
- );
-
- SDiagnostic::new(
- d.with_file_path(params.path.as_path().display().to_string())
- .with_file_span(r)
- .with_severity(severity),
- )
+ let mut diagnostics: Vec<SDiagnostic> = vec![];
+
+ // run diagnostics for each statement in parallel if its mostly i/o work
+ if let Some(pool) = self.connection.read().unwrap().get_pool() { | Nit: `.read().and_then(|p| p.get_pool())` ?
Not sure if there could ever be a `None` in `self.connection` |
postgres_lsp | github_2023 | others | 169 | supabase-community | juleswritescode | @@ -336,50 +339,95 @@ impl Workspace for WorkspaceServer {
filter,
});
- let diagnostics: Vec<SDiagnostic> = doc
- .iter_statements_with_range()
- .flat_map(|(stmt, r)| {
- let mut stmt_diagnostics = vec![];
-
- stmt_diagnostics.extend(self.pg_query.get_diagnostics(&stmt));
- let ast = self.pg_query.get_ast(&stmt);
- if let Some(ast) = ast {
- stmt_diagnostics.extend(
- analyser
- .run(AnalyserContext { root: &ast })
- .into_iter()
- .map(SDiagnostic::new)
- .collect::<Vec<_>>(),
- );
- }
-
- stmt_diagnostics
- .into_iter()
- .map(|d| {
- // We do now check if the severity of the diagnostics should be changed.
- // The configuration allows to change the severity of the diagnostics emitted by rules.
- let severity = d
- .category()
- .filter(|category| category.name().starts_with("lint/"))
- .map_or_else(
- || d.severity(),
- |category| {
- settings
- .as_ref()
- .get_severity_from_rule_code(category)
- .unwrap_or(Severity::Warning)
- },
- );
-
- SDiagnostic::new(
- d.with_file_path(params.path.as_path().display().to_string())
- .with_file_span(r)
- .with_severity(severity),
- )
+ let mut diagnostics: Vec<SDiagnostic> = vec![];
+
+ // run diagnostics for each statement in parallel if its mostly i/o work
+ if let Some(pool) = self.connection.read().unwrap().get_pool() {
+ let typecheck_params: Vec<_> = doc
+ .iter_statements_with_text_and_range()
+ .map(|(stmt, range, text)| {
+ let ast = self.pg_query.get_ast(&stmt);
+ let tree = self.tree_sitter.get_parse_tree(&stmt);
+ (text.to_string(), ast, tree, *range)
+ })
+ .collect();
+
+ let pool_clone = pool.clone();
+ let path_clone = params.path.clone();
+ let async_results = run_async(async move {
+ stream::iter(typecheck_params)
+ .map(|(text, ast, tree, range)| {
+ let pool = pool_clone.clone();
+ let path = path_clone.clone();
+ async move {
+ if let Some(ast) = ast {
+ pg_typecheck::check_sql(TypecheckParams {
+ conn: &pool,
+ sql: &text,
+ ast: &ast,
+ tree: tree.as_deref(),
+ })
+ .await
+ .map(|d| {
+ let r = d.location().span.map(|span| span + range.start());
+
+ d.with_file_path(path.as_path().display().to_string())
+ .with_file_span(r.unwrap_or(range))
+ })
+ } else {
+ None
+ }
+ }
})
+ .buffer_unordered(10) | that's a nice API 🙃 |
postgres_lsp | github_2023 | others | 169 | supabase-community | juleswritescode | @@ -0,0 +1,217 @@
+use std::io;
+
+use pg_console::markup;
+use pg_diagnostics::{Advices, Diagnostic, LogCategory, MessageAndDescription, Severity, Visit};
+use sqlx::postgres::{PgDatabaseError, PgSeverity};
+use text_size::TextRange;
+
+/// A specialized diagnostic for the typechecker.
+///
+/// Type diagnostics are always **errors**.
+#[derive(Clone, Debug, Diagnostic)]
+#[diagnostic(category = "typecheck")]
+pub struct TypecheckDiagnostic {
+ #[location(span)]
+ span: Option<TextRange>,
+ #[description]
+ #[message]
+ message: MessageAndDescription,
+ #[advice]
+ advices: TypecheckAdvices,
+ #[severity]
+ severity: Severity,
+}
+
+#[derive(Debug, Clone)]
+struct TypecheckAdvices {
+ code: String,
+ schema: Option<String>,
+ table: Option<String>,
+ column: Option<String>,
+ data_type: Option<String>,
+ constraint: Option<String>,
+ line: Option<usize>,
+ file: Option<String>,
+ detail: Option<String>,
+ routine: Option<String>,
+ where_: Option<String>,
+ hint: Option<String>,
+}
+
+impl Advices for TypecheckAdvices {
+ fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
+ // First, show the error code
+ visitor.record_log(
+ LogCategory::Error,
+ &markup! { "Error Code: " <Emphasis>{&self.code}</Emphasis> },
+ )?;
+
+ // Show detailed message if available
+ if let Some(detail) = &self.detail {
+ visitor.record_log(LogCategory::Info, &detail)?;
+ }
+
+ // Show object location information
+ if let (Some(schema), Some(table)) = (&self.schema, &self.table) {
+ let mut location = format!("In table: {schema}.{table}");
+ if let Some(column) = &self.column {
+ location.push_str(&format!(", column: {column}"));
+ }
+ visitor.record_log(LogCategory::Info, &location)?;
+ }
+
+ // Show constraint information
+ if let Some(constraint) = &self.constraint {
+ visitor.record_log(
+ LogCategory::Info,
+ &markup! { "Constraint: " <Emphasis>{constraint}</Emphasis> },
+ )?;
+ }
+
+ // Show data type information
+ if let Some(data_type) = &self.data_type {
+ visitor.record_log(
+ LogCategory::Info,
+ &markup! { "Data type: " <Emphasis>{data_type}</Emphasis> },
+ )?;
+ }
+
+ // Show context information
+ if let Some(where_) = &self.where_ {
+ visitor.record_log(LogCategory::Info, &markup! { "Context:\n"{where_}"" })?;
+ }
+
+ // Show hint if available
+ if let Some(hint) = &self.hint {
+ visitor.record_log(LogCategory::Info, &markup! { "Hint: "{hint}"" })?;
+ }
+
+ // Show source location if available
+ if let (Some(file), Some(line)) = (&self.file, &self.line) {
+ if let Some(routine) = &self.routine {
+ visitor.record_log(
+ LogCategory::Info,
+ &markup! { "Source: "{file}":"{line}" in "{routine}"" },
+ )?;
+ } else {
+ visitor.record_log(LogCategory::Info, &markup! { "Source: "{file}":"{line}"" })?;
+ }
+ }
+
+ Ok(())
+ }
+}
+
+pub(crate) fn create_type_error(
+ pg_err: &PgDatabaseError,
+ ts: Option<&tree_sitter::Tree>,
+) -> TypecheckDiagnostic {
+ let position = pg_err.position().and_then(|pos| match pos {
+ sqlx::postgres::PgErrorPosition::Original(pos) => Some(pos - 1),
+ _ => None,
+ });
+
+ let range = position.and_then(|pos| {
+ ts.and_then(|tree| {
+ tree.root_node()
+ .named_descendant_for_byte_range(pos, pos)
+ .map(|node| {
+ TextRange::new(
+ node.start_byte().try_into().unwrap(),
+ node.end_byte().try_into().unwrap(), | I'm not 100% sure, but I think `TextRange::end` is _exclusive_ – maybe we need to add 1 here |
postgres_lsp | github_2023 | others | 167 | supabase-community | juleswritescode | @@ -26,8 +26,7 @@ pub fn parse(sql: &str) -> Result<NodeEnum> {
.nodes()
.iter()
.find(|n| n.1 == 1)
- .unwrap()
- .0
- .to_enum()
- })
+ .map(|n| n.0.to_enum())
+ .ok_or_else(|| Error::Parse("Unable to find root node".to_string())) |  |
postgres_lsp | github_2023 | others | 167 | supabase-community | juleswritescode | @@ -368,7 +368,7 @@ impl Pattern {
/// `Pattern` using the default match options (i.e. `MatchOptions::new()`).
pub fn matches_path(&self, path: &Path) -> bool {
// FIXME (#9639): This needs to handle non-utf8 paths
- path.to_str().map_or(false, |s| self.matches(s))
+ path.to_str().is_some_and(|s| self.matches(s)) | these changes come from the `lint` in the justfile, right? awesome! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.