Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will context be used as default in the entire sql transaction?

I was wondering if you start a transaction with a context if the whole transaction will "listen" to that context here?

tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
stmt, _ := tx.Prepare("SELECT id, timeout, lang FROM client WHERE id=?")

Or do you explicitly apply the context to each query?

tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
stmt, _ := tx.PrepareContext(ctx, "SELECT id, timeout, lang FROM client WHERE id=?")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No. Prepare, and other contextless methods, use context.Background.

From the Tx.Prepare docs

Prepare uses context.Background internally; to specify the context, use PrepareContext.

Looking at the source code, it’s just a simple wrapper.

func (tx *Tx) Prepare(query string) (*Stmt, error) {
    return tx.PrepareContext(context.Background(), query)
}

I assume this is because you’re not supposed to store Contexts in structs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading