uptrace / bun

SQL-first Golang ORM
https://bun.uptrace.dev
BSD 2-Clause "Simplified" License
3.46k stars 206 forks source link

feat: add mechanism for prefixing queries with a comment string #1002

Open kylemcc opened 5 days ago

kylemcc commented 5 days ago

This change proposes a new Comment(string) method and ContextWithComment(context.Context, string) function for prepending a comment to a SQL query.

Here's simple example:

// using the query API
err := db.NewSelect().
    Model(&products).
    Where("description like ?", d).
    Comment("customer:"+customerID).
    Scan(ctx)

// using a context
qctx := bun.ContextWithComment(ctx, "customer:"+customerID)
err := db.NewSelect().
    Model(&products).
    Where("description LIKE ?", d).
    Scan(qctx)

This would produce a query that looks like:

/*customer:01J1P97P3AP7V287B57P7055CZ*/ SELECT * FROM products WHERE description LIKE '%red%'

This may warrant a bit of discussion first, but I wanted to include the code with the proposal. I have had this code running in production since April with no problems. It appears that others may be interested in this as well: https://github.com/uptrace/bun/issues/998

My immediate use case for this is to add a comment to a query with tracing/debug information that will show up in the process list/pg_stat_activity, but there are certainly other uses for this functionality.