vendredi 30 avril 2021

Dynamically add before/after logic to a class

I have a generic class that holds logic for running queries against a database. I want to be able to add "before" and "after" queries to the actual queries.

For instance, say I have a class that holds some UPDATE TABLE logic on the database, and I want to run before that query something that changes the session parameters, and reverts them upon finish.

Thing is, these classes are reusable, and I want to be able to parametrize these before/after queries (So a class can choose them upon instantiation)

class UpdateTableBasedOnStuff(QueryRunner):
    # Query runner holds logic to running the built queries
    def __init__(self, ...):
        ...

    def build_queries(self, table, condition):
        query = create_query_from_params(table, fields_to_update, condition)
        return [query]

So one query might want to run this thing with a user "ADMIN" and another with the user "APP", and another query might want to SET some session variables before running this. So there's some form of reusability I'd like to incorporate here, but I'm not sure what's the best approach.

Generally I'd consider the best approach the one that will let me simply pass parameters for these. e.g:

_ = UpdateTableBasedOnStuff(...,user="APP")

But I suppose there are merits to this approach as well, so having something like this might suit too:

_ = UpdateTableBasedOnStuff(...,before="SET USER = \"APP\"", after="...")

Generally I'd be glad if anyone can shed some light about the situation, and recommendations I haven't thought of.

Several things I've considered:

  1. Having optional before/after methods for the base class.
  2. Decorators, but this is a bit limiting, since I want these to be dynamic upon instantiation
  3. Utilizing context managers, but I do not see a viable way to add this to our current design.

Thank you for any form of help :)

Aucun commentaire:

Enregistrer un commentaire