Query log event doesn't quote datetimes in query params
Bug description
I was following this - https://medium.com/@lucas_18321/how-to-trace-sql-queries-in-prisma-with-xray-sdk-in-nodejs-8c6dc92df07f
Which works fine except for one thing - when it parses the query params
const paramsArr = JSON.parse(e.params)
e.params is JSON except when there is a Date object in there. or newlines.
Looks like:
"params":"[2022-03-30 11:52:45.302 UTC,\"1.0\",\"0f8b1ad3-8c7a-4da9-bdfd-0f326e061caf\",\"467f19ec-3589-424f-b512-07e62003eee1\"]"
Here's how I'm working around it right now
// parse parameters JSON
// we need to fix quoting of datetimes
// e.g. [2022-03-30 11:52:45.302 UTC,"1.0"]
const paramsStr = e.params.replace(/(\d{4}-\d{2}-\d{2} \d+:\d+:\d+\.\d+ UTC)/g, '"$1"').replace(/\n/g, " ")
let params: string[] = []
try {
params = JSON.parse(paramsStr)
} catch (e) {
console.warn("Failed parsing params JSON:", paramsStr, e)
}
How to reproduce
Expected behavior
No response
Prisma information
Environment & setup
- OS:
- Database:
- Node.js version:
Prisma Version
Also I think double-quotes and newlines are not escaped
This seems to still be an issue on 4.8.1. I experience it when submitting a query using Prisma with a JsonObject value. I think it'd just be simpler to have the e.params value (in the logging callbacks) just be an array of values rather than a string representation of the parameters for the prepared statements.
The way I had been mitigating it was by using JSON.parse on the params value, except this time it's been throwing errors because the quotes in the JSON representation of my cookie object (the value I'm storing as a JsonObject) is not escaped properly and causes the JSON parsing to fail in my logging callback.
Here's a simplified example:
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient({
log: [{
level: "query",
emit: "event"
}]
});
function replacePreparedParams(query: string, params: string[]) {
const replacer = () => JSON.stringify(params.shift());
return query.replace(/\?/g, replacer);
}
prisma.$on("query", e => {
// This is the line that causes the error:
const parsed_params = JSON.parse(e.params);
console.log(replacePreparedParams(e.query.trim(), parsed_params));
});
The error looks something like this (with some irrelevant data elided):
["...","{"cookie":{"originalMaxAge":86400000,"expires":"2023-01-09T09:13:35.195Z","httpOnly":true,"path":"/"},"passport":{"user":"..."}}","...","..."]
^
SyntaxError: Unexpected token c in JSON at position 34
at JSON.parse (<anonymous>)
at <anonymous> (/app/src/managers/PrismaManager.ts:36:34)
at EventEmitter.<anonymous> (/app/node_modules/@prisma/client/runtime/index.js:35690:20)
at EventEmitter.emit (node:events:513:28)
at LibraryEngine.logger (/app/node_modules/@prisma/client/runtime/index.js:27758:23)
at /app/node_modules/@prisma/client/runtime/index.js:27730:61
Running npx prisma version returns the following:
$ npx prisma version
Environment variables loaded from .env
prisma : 4.8.1
@prisma/client : 4.8.1
Current platform : debian-openssl-3.0.x
Query Engine (Node-API) : libquery-engine d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/libquery_engine-debian-openssl-3.0.x.so.node)
Migration Engine : migration-engine-cli d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/migration-engine-debian-openssl-3.0.x)
Introspection Engine : introspection-core d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/introspection-engine-debian-openssl-3.0.x)
Format Binary : prisma-fmt d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/prisma-fmt-debian-openssl-3.0.x)
Format Wasm : @prisma/prisma-fmt-wasm 4.8.0-61.d6e67a83f971b175a593ccc12e15c4a757f93ffe
Default Engines Hash : d6e67a83f971b175a593ccc12e15c4a757f93ffe
Studio : 0.479.0
Hope this helps.
query params are generally unparsable, unfortunately. I wanted this for the purpose of writing data (not DDL) migrations in prisma, as doing so in raw sql would be pretty horrific in a db managed by prisma.
after trial and error and research, I landed on enabling the postgres query log in my local database, writing a function that takes a prisma query thunk as an argument, and setting log_statement to mod prior to running the query, then setting it to off after running the query -- this way, only queries I intend to include in the migration get logged. I then read the log, run it through awk for some basic filtering (awk '{if($6~/^execute/){$1=$2=$3=$4=$5=$6=$7=\"\";print $0}else if($6~/^parameters/){$1=$2=$3=$4=$5=$6=\"\";print $0}}'), then my migration.ts uses a helper to turn the query/params rows from the log into something that looks like the following for the migration.sql file:
DO $$
BEGIN
EXECUTE 'UPDATE "public"."BaseProtocol" SET "name" = $1, "description" = $2 WHERE ("public"."BaseProtocol"."id" IN ($3) AND ("public"."BaseProtocol"."id" = $4 AND 1=1))'
USING 'FooBar', NULL, 'b5840e54-36c4-40b0-9eae-39e14dae02bb', 'b5840e54-36c4-40b0-9eae-39e14dae02bb';
END
$$;
the only aspect that's not fully generic is defining transformations on params to cast things into their appropriate types (e.g. an enum "MyEnum" with FOO and BAR will be represented in the query log as the string 'FOO' or 'BAR', which you'll want to change to e.g. 'FOO'::"MyEnum". I made my code pluggable to add custom transformations, and I can always modify the resulting migration.sql by hand if needed.
afaict this is the most reliable workflow possible today, and the limitation described in the last paragraph is totally reasonable to deal with in practice. don't be like me and try to build such functionality using prisma query events and chasing down edge cases trying to parse params, which is ultimately lossy in a way you can't fix in code.
This issue was fixed in the Prisma Client 4.3 and have a fix for it here https://github.com/prisma/prisma/pull/14876, so I am closing this issue. Thanks for the reports.
@millsp datetimes were just part of the problem. has serialization been fixed to be a real format, or was this a one off "fix"?
Sure. Do you agree that this belongs in a different issue as it is broader than the OP? If so, could you please open a new issue with the information we need and how you'd actually expect it to behave, maybe as a feature request or an improvement? Thanks.
There are many existing issues that stem from this cause, many of which I've contributed to, and I'd invite any member of the prisma team to take ownership of this bug (not feature, not enhancement -- it's a documented feature that does not work) to improve the core product, including documenting it in the preferred fashion. Surely someone with access to contribute to the rust codebase could add a few well placed derive Serialize/Deserialize and make quick work of this.
On Thu, Aug 24, 2023, 9:13 PM pierre @.***> wrote:
Sure. Do you agree that this belongs in a different issue as it is broader than the OP? If so, could you please open a new issue with the information we need and how you'd actually expect it to behave, maybe as a feature request or an improvement? Thanks.
— Reply to this email directly, view it on GitHub https://github.com/prisma/prisma/issues/12591#issuecomment-1692615235, or unsubscribe https://github.com/notifications/unsubscribe-auth/A2S7EQ6ZOH2DEYC6SRPUNO3XW734LANCNFSM5SCHBINA . You are receiving this because you commented.Message ID: @.***>
Can you point us to these issues @revero-doug, please?
Right now, none of them are cross-linked in this issue in any way (both comments or issue history) - so we fixed the datetime problem and consider this issue resolved, as it only asked for datetime. If there were links to other issues, we could probably have resolved these problems as well.
Thank you.
(PRs welcome as well of course if that is a thing that is an option for you.)