Masterminds / squirrel

Fluent SQL generation for golang
Other
6.98k stars 465 forks source link

How to specify a schema for PostgreSQL #80

Closed msaron closed 7 years ago

msaron commented 7 years ago

How can one specify a schema when creating a query for PostgreSQL. In NodeJS library called KnexJS, one can specify schema name like knex('tablename').schema('public').where(...) I have a database that has a schema for each client and I need to switch the schema dynamically based on the schema linked to that user for each request. Thanks.

msaron commented 7 years ago

I don't think the knex('tablename').schema('public').where(...) code is a good idea because what if you are pulling data from multiple schemas. Then this code would cause problems.

msaron commented 7 years ago

Figured out an efficient way to do this. Here is how.

tn := fmt.Sprintf("%q.city", "public")
sql := sq.Select("*").From(tn) // sql = SELECT * FROM "public".city

In case you are using the PostgreSQL driver, you can use the following code.

import "github.com/lib/pq"

tn := fmt.Sprintf("%s.city", pq.QuoteIdentifier("public"))
sql := sq.Select("*").From(tn) // sql = SELECT * FROM "public".city