-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 00be5c0
Showing
13 changed files
with
2,505 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
name: Lint | ||
|
||
on: | ||
push: | ||
branches: | ||
- master | ||
|
||
pull_request: | ||
branches: | ||
- '*' | ||
|
||
jobs: | ||
lint: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Git checkout | ||
uses: actions/checkout@v4 | ||
|
||
- name: Install node | ||
uses: actions/setup-node@v4 | ||
with: | ||
node-version: 20 | ||
cache: yarn | ||
|
||
- name: Install dependencies | ||
run: yarn --frozen-lockfile | ||
|
||
- name: Check types | ||
run: yarn typecheck | ||
|
||
test: | ||
needs: lint | ||
if: ${{ needs.lint.result == 'success' }} | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Git checkout | ||
uses: actions/checkout@v4 | ||
|
||
- name: Install node | ||
uses: actions/setup-node@v4 | ||
with: | ||
node-version: 20 | ||
cache: yarn | ||
|
||
- name: Install dependencies | ||
run: yarn --frozen-lockfile | ||
|
||
- name: Run tests | ||
run: yarn test |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
name: Publish | ||
|
||
on: | ||
release: | ||
types: [released] | ||
|
||
jobs: | ||
publish: | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- name: Git checkout | ||
uses: actions/checkout@v4 | ||
|
||
- name: Install node | ||
uses: actions/setup-node@v4 | ||
with: | ||
node-version: 20 | ||
registry-url: 'https://registry.npmjs.org' | ||
cache: yarn | ||
|
||
- name: Install dependencies | ||
run: yarn --frozen-lockfile | ||
|
||
- name: Build package | ||
run: yarn build | ||
|
||
- name: Publish to registry | ||
run: npm publish | ||
env: | ||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
.DS_Store | ||
Thumbs.db | ||
|
||
.idea | ||
.vscode | ||
|
||
dist | ||
node_modules | ||
yarn-error.log |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"printWidth": 120, | ||
"tabWidth": 2, | ||
"semi": true, | ||
"singleQuote": false, | ||
"trailingComma": "all" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 Dan L | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# Prisma Query Formatter | ||
|
||
This is small, zero-dependency utility correctly stringifies Prisma queries by substituting placeholders with their corresponding values (internally, Prisma uses its own Rust implementation for stringifying params). | ||
|
||
Keep in mind that this utility is designed solely for logging purposes, and Prisma irreversibly transforms certain parameter types, such as [blobs](https://github.com/prisma/prisma-engines/blob/5.13.0/quaint/src/ast/values.rs#L571). | ||
|
||
## How to use it | ||
|
||
Just register a query event handler and use the `formatPrismaQuery` util to substitute the query params (don't forget to enable [event-based](https://www.prisma.io/docs/orm/reference/prisma-client-reference#log) logging in your Prisma client configuration). | ||
|
||
```typescript | ||
import { PrismaClient } from "@prisma/client"; | ||
import { formatQuery } from "prisma-query-formatter"; | ||
|
||
const prisma = new PrismaClient({ | ||
log: [ | ||
{ emit: "event", level: "query" }, | ||
], | ||
}); | ||
|
||
prisma.$on("query", (e) => { | ||
console.log(formatQuery(e.query, e.params)); | ||
}); | ||
``` | ||
|
||
For example, this query: | ||
|
||
```typescript | ||
await db.user.findUnique({ | ||
select: { id: true }, | ||
where: { email: "john@example.com" }, | ||
}); | ||
``` | ||
|
||
Will be logged to the console as: | ||
|
||
```text | ||
SELECT `example`.`User`.`id` FROM `example`.`User` WHERE (`example`.`User`.`email` = "john@example.com" AND 1=1) LIMIT 1 OFFSET 0 | ||
``` | ||
|
||
## Query formatting | ||
|
||
All whitespace symbols in multiline queries (usually raw queries written manually) will be replaced with single space, for example: | ||
|
||
```typescript | ||
await db.$queryRaw` | ||
SELECT | ||
DISTINCT role | ||
FROM User | ||
WHERE | ||
status = ${Status.Active} | ||
`; | ||
``` | ||
|
||
Will be logged with params as: | ||
|
||
```text | ||
SELECT DISTINCT role FROM User WHERE status = "Active" | ||
``` | ||
|
||
To escape whitespace symbols like `\f\n\r\t\v` in the params, use the `escapeParams` option, this will allow you to make your logs more concise. | ||
|
||
```typescript | ||
prisma.$on("query", (e) => { | ||
console.log(formatQuery(e.query, e.params, { escapeParams: true })); | ||
}); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
/** @type {import("jest").Config} */ | ||
const config = { | ||
roots: ["<rootDir>/src/", "<rootDir>/tests/"], | ||
preset: "ts-jest", | ||
testEnvironment: "node", | ||
testMatch: ["<rootDir>/tests/**/*.test.ts"], | ||
}; | ||
|
||
module.exports = config; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
{ | ||
"name": "prisma-query-formatter", | ||
"version": "0.1.0", | ||
"description": "Small utility for Prisma query formatting and param substitution", | ||
"license": "MIT", | ||
"keywords": [ | ||
"prisma", | ||
"query", | ||
"logging" | ||
], | ||
"author": "s1owjke", | ||
"homepage": "https://github.com/s1owjke/prisma-query-formatter", | ||
"main": "dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"files": [ | ||
"dist" | ||
], | ||
"scripts": { | ||
"build": "rm -rf dist && tsc", | ||
"build:watch": "rm -rf dist && tsc --watch", | ||
"typecheck": "tsc --noEmit", | ||
"test": "jest" | ||
}, | ||
"devDependencies": { | ||
"@types/jest": "^29.5.12", | ||
"jest": "^29.7.0", | ||
"ts-jest": "^29.1.2", | ||
"typescript": "^5.4.5" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
type FormatOptions = { | ||
escapeParams?: boolean; | ||
}; | ||
|
||
const escapeWhitespace = (param: string) => { | ||
return param.replace(/[\f\n\r\t\v]/g, (match) => { | ||
if (match === "\f") return "\\f"; | ||
if (match === "\n") return "\\n"; | ||
if (match === "\r") return "\\r"; | ||
if (match === "\t") return "\\t"; | ||
if (match === "\v") return "\\v"; | ||
return match; | ||
}); | ||
}; | ||
|
||
export const parseParams = (rawParams: string) => { | ||
const values = rawParams.replace(/^\[([^]*)]$/, "$1"); | ||
return values ? values.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/) : []; | ||
}; | ||
|
||
export const formatQuery = (query: string, rawParams: string, options: FormatOptions = {}): string => { | ||
const params = parseParams(rawParams); | ||
|
||
query = query.replace(/\s/g, " ").replace(/\s{2,}/g, " "); | ||
|
||
if (params.length > 0) { | ||
query = query.replace(/(\?|\$\d+)/g, () => { | ||
const param = params.shift() || ""; | ||
return options.escapeParams ? escapeWhitespace(param) : param; | ||
}); | ||
} | ||
|
||
return query.trim(); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { formatQuery } from "../src"; | ||
|
||
describe("query formatting", () => { | ||
test("without params", () => { | ||
const log = formatQuery("SELECT COUNT(*) FROM Post", `[]`); | ||
expect(log).toEqual(`SELECT COUNT(*) FROM Post`); | ||
}); | ||
|
||
test("with params", () => { | ||
const log = formatQuery("SELECT * FROM Post WHERE status = ? AND views >= ?", `["active",500]`); | ||
expect(log).toEqual(`SELECT * FROM Post WHERE status = "active" AND views >= 500`); | ||
}); | ||
|
||
test("whitespace cleanup", () => { | ||
const log = formatQuery("SELECT\n COUNT(*)\nFROM\n Post\nWHERE\n status = ?", `["active"]`); | ||
expect(log).toEqual(`SELECT COUNT(*) FROM Post WHERE status = "active"`); | ||
}); | ||
|
||
test("trailing whitespace cleanup", () => { | ||
const log = formatQuery("\nSELECT COUNT(*) FROM Post\n", `[]`); | ||
expect(log).toEqual(`SELECT COUNT(*) FROM Post`); | ||
}); | ||
|
||
test("without params escaping", () => { | ||
const log = formatQuery("SELECT * FROM Post WHERE content = ?", `[" \f\n\r\t\v"]`); | ||
expect(log).toEqual(`SELECT * FROM Post WHERE content = " \f\n\r\t\v"`); | ||
}); | ||
|
||
test("with params escaping", () => { | ||
const log = formatQuery("SELECT * FROM Post WHERE content = ?", `[" \f\n\r\t\v"]`, { escapeParams: true }); | ||
expect(log).toEqual(`SELECT * FROM Post WHERE content = " \\f\\n\\r\\t\\v"`); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { parseParams } from "../src"; | ||
|
||
describe("params parsing", () => { | ||
test("empty array", () => { | ||
expect(parseParams("[]")).toEqual([]); | ||
}); | ||
|
||
test("numbers", () => { | ||
expect(parseParams("[1,2,3]")).toEqual(["1", "2", "3"]); | ||
}); | ||
|
||
test("single-line strings", () => { | ||
expect(parseParams(`["one","two","three"]`)).toEqual([`"one"`, `"two"`, `"three"`]); | ||
}); | ||
|
||
test("multi-line strings", () => { | ||
expect(parseParams(`["first line\r\nsecond line"]`)).toEqual([`"first line\r\nsecond line"`]); | ||
}); | ||
|
||
test("string with nested quotes", () => { | ||
expect(parseParams(`["value with "nested" quotes"]`)).toEqual([`"value with "nested" quotes"`]); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{ | ||
"compilerOptions": { | ||
"declaration": true, | ||
"esModuleInterop": true, | ||
"forceConsistentCasingInFileNames": true, | ||
"lib": ["es2020"], | ||
"module": "commonjs", | ||
"outDir": "./dist", | ||
"skipLibCheck": true, | ||
"strict": true, | ||
"target": "es2020", | ||
}, | ||
"include": ["./src"], | ||
"exclude": ["node_modules"] | ||
} |
Oops, something went wrong.