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

Middleware/wrapper to wrap all queries in a transaction #6038

Open
ksorensen76 opened this issue Mar 18, 2024 · 0 comments
Open

Middleware/wrapper to wrap all queries in a transaction #6038

ksorensen76 opened this issue Mar 18, 2024 · 0 comments

Comments

@ksorensen76
Copy link

ksorensen76 commented Mar 18, 2024

Environment

Knex version: Knex 3.0.1
Database + version: PostgreSQL 14.11
OS: Ubuntu

Feature discussion / request

I am working on automating audit logging for a Next.js application. I have a trigger function set up to run on insert/update/delete and the issue comes when trying to pass the application user's id (not the PostgreSQL user) to the trigger. I have got it working manually with the following code, but would like to be able to wrap all queries in the transaction to automate things a bit more.

    const result = await db().transaction(async (trx) => {
      await trx.raw('SET LOCAL my_app.app_session_user = ${session.user.id}')
      const insert = await trx.insert(data)
        .into('${schema}.${tableName}')
      return insert
    })

Is there currently a middleware or other method to wrap the insert query above, adding the transaction and setting the app_session_user to all queries automatically so it can be accessed in the trigger function?

Or maybe I am thinking about this all wrong, if so, any suggestions on a better method would be appreciated.

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

No branches or pull requests

1 participant