Skip to content

Feature Request: Hooks #1720

Open
Open
@jlemesh

Description

@jlemesh

I am currently using the go-sql-driver/mysql package for managing MySQL transactions. I am facing a challenge where I need to embed SQL comments at the start (START TRANSACTION) and end (COMMIT, ROLLBACK) of transactions for database issues debugging purposes. I would also like to add some transaction query validation, where I need to track all the queries of a single transaction. However, the existing transaction methods do not allow for direct embedding of such functionality.

I suggest implementing hooks that would allow developers to inject SQL comments or other custom logic. Specifically, introducing execWithContext method could address this:

  • Add hooks global variable and functions to set it to accept hooks that developers can supply:
var hooks = make(map[string]Hook)

func RegisterHook(name string, hook Hook) {
   if hook == nil {
      return
   }
   hooks[name] = hook
}
  • Hook is an interface:
type Hook interface {
   OnSQL(ctx context.Context, query string) (string, error)
}
  • Create new function execWithContext that execute hooks prior to the SQL command. This would also allow modyfying the query (for adding comments):
func (mc *mysqlConn) execWithContext(ctx context.Context, query string) error {
   if len(hooks) > 0 {
      for _, hook := range hooks {
         query, err := hook.OnSQL(ctx, query)
         if err != nil {
            return fmt.Errorf("failed to run query: %s", err)
         }
      }
   }
   return mc.exec(query)
}

This method should be used instead of exec where context is present.

  • Similar method is also needed for query

  • mysqlTx (or new struct, e. g. mysqlTxWithCtx) should also be able to store context, and call execWithContext (in case BeginTx was called).

Could you provide guidance on whether this approach aligns with the project’s direction and feasibility within the current architecture? Additionally, are there existing patterns or alternative solutions recommended by the community for achieving same results?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions