Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support queries with parameters #384

Open
mmkal opened this issue Mar 4, 2024 · 2 comments · May be fixed by #385
Open

Support queries with parameters #384

mmkal opened this issue Mar 4, 2024 · 2 comments · May be fixed by #385

Comments

@mmkal
Copy link

mmkal commented Mar 4, 2024

Hi! Love pg-mem.

One thing that's a little awkward to do is to pass queries that have parameters to it (e.g., which have come from pg-promise or slonik similar).

So say I've got an object that looks like { sql: 'select * from foo where id = $1', values: ['abc'] } - I'd love to be able to pass them straight to pg-mem and have it work. (like db.public.query(myQuery.sql, myQuery.values)).

Right now I've got a terrible workaround which works for the very limited use-case I have so far, but I think it will break as soon as I do something more complex, so I'm thinking there's already a better way, or if not, there could be:

let statement = pgSqlAstParser.parse(query.sql)

statement = JSON.parse(JSON.stringify(statement), (key, value) => {
  if (value?.type === 'parameter' && typeof value?.name === 'string') {
    const literalValue = query.values[Number(value.name.slice(1)) - 1]
    return {type: 'string', value: literalValue}
  }
  return value
})

return fakeDb.public.query(statement)

If this is already possible, it can become a docs request.

@taironoaky
Copy link

+1 on this.

@marcus13371337
Copy link

There is some code that does exactly this in this repo already:

function replaceQueryArgs$(this: void, sql: string, values: any[]) {

Maybe just export that as a common util?

@mmkal mmkal linked a pull request Mar 6, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants