adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.02k stars 189 forks source link

.useTransaction() is ignored and the default connection is used #1004

Closed shaheedazaad closed 3 months ago

shaheedazaad commented 4 months ago

Package version

20.1.0

Describe the bug

I'm aware that .useTransaction() is deprecated at this point, but it might also be broken unless I've misunderstood how it works.

Here's my code: I'm trying to update and delete a user using a transaction on a particular connection.

    //finds user as expected
    const user = await User.firstOrFail({ connection: getTenantInfo().connection })

    //connects to a database that exists
    const trx = await db.connection(getTenantInfo().connection).transaction()

    //works as expected
    await trx.query().update({ first_name: 'test' }).from('users').where('id', user.id)

    user.useTransaction(trx)

    //fails because the database on the primary connection doesn't exist
    await user.delete()

    await trx.rollback()

user.delete() doesn't seem to use the transaction, I get an error implying that it's trying to use the primary connection (because the database for that one doesn't exist). Inspecting the trx object shows that it's using the correct connection - this is confirmed by trx.query() working as expected.

Reproduction repo

No response

thetutlage commented 4 months ago

Not sure I get the issue properly. Is that that the trx is using a different database connection and the Model is using a different database connection?

shaheedazaad commented 4 months ago

Not sure I get the issue properly. Is that that the trx is using a different database connection and the Model is using a different database connection?

That's right. It looks like the trx is set correctly for the model, when I check with user.$trx. Now I've found that await user.save() also works as expected.

I wonder if it's specific to the .delete() method. I did use the lucid-softdeletes package when I was on v5, but I am pretty sure I removed everything related to that already.

thetutlage commented 4 months ago

Looking the code, the delete method should work same the save method. Can you dig into the node_modules and check if this method receives the correct transaction? https://github.com/adonisjs/lucid/blob/develop/src/orm/base_model/index.ts#L2012

RomainLanz commented 3 months ago

Closing since no answer from issue reporter.