jackc / pgx

PostgreSQL driver and toolkit for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

User / custom values storage on pgconn.PgConn

jackc opened this issue · comments

Sometimes it is useful to attach an arbitrary value to a connection. I believe this has previously been indirectly requested multiple times, but at the moment I am unable to find the issues where it was mentioned.

But one possible use is adding a pointer to containing objects such as a connection pool. This could be useful for pgconn level hooks that may want to reference their containing pool. Another use is to provide another way of passing arbitrary data to tracing or logging hooks.

I propose adding a map of custom attributes to pgconn.PgConn.

Possible interfaces include:

  1. Adding a method that returns the map.
  2. Adding get and set attribute methods.

I lean toward option 2 as that would allow making access concurrency safe.

This is something I needed in the context of #1971, to know what the notice origin is.

I was thinking that it would be enough to just have customData interface{} field on the connection. You could then manipulate it yourself as you see fit in connection acquire/release hooks. You could add a lock yourself if you need it as well there.

But having a map so that multiple different pieces of code each add their own data might be reasonable as well. Not sure if concurrency safety is really needed by default? It will be probably mostly data you write once (at connection acquire) and then just read? I think if you want to modify value there multiple times, you can always store it wrapped with a lock.