How to specify schema for Postgres in Golang?

Viewed 688

I have a database that stores customer data in different schemas(schema per tenant). I need to be able to dynamically set the schema name upon the execution of a query. My problem is that I run those queries upon a web request using gin, and I have multiple threads running at the same time. So basically doing this

_, err = db.Exec(fmt.Sprintf("set search_path to %s", schemaName))
if err != nil {
    panic(err)
}

// GAP

var queryStr = "select * from customer_data"

query, err := db.Query(queryStr)
if err != nil {
    panic(err)
}
defer query.Close()

works fine when executed in a single thread environment, but from a web server perspective, that's too unreliable, because I can end up requesting data from customer 1 and getting from customer 2, because during the GAP specified in the code, the other thread can call set search_path query.

0 Answers
Related