tortoise / tortoise/tortoise-orm

Init function run on each connection?

Open
#1,964 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

USER CASE
Currently for every query I need to do something like below

        async with in_transaction("default") as conn:
            await conn.execute_script(f"SET LOCAL app.some_id = 'abc';")
            # rest of queries after this; e.g. await User.all()

IDEAL SOLUTION
A hook or similar, allowing to run some initial setup when a new connection is created. Or some documentation on how to properly override the "connection manager".

THINGS TRIED
Overriding QuerySet but that doesn't seem to have access to connection directly? Feels maybe not the right place.

I've also tried to monkey-patch the connection handlers but had little success..

# Monkey-patch Tortoise's ConnectionHandler for custom connection init setup
class CustomConnectionHandler(ConnectionHandler):
    def _create_connection(self, conn_alias):
        conn = super()._create_connection(conn_alias)
        
        # Never gets here ..
        
        return conn
tortoise.connection.connections = CustomConnectionHandler()

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the connection lifecycle around ConnectionHandler and the in_transaction usage described in the issue; compare that with the QuerySet and monkey-patching approaches already tried. A complete change would provide a supported connection-initialization hook or clear documentation for overriding the connection manager, with coverage showing setup runs when a new connection is created.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.