Search code examples
google-app-enginegogoogle-cloud-datastoregoogle-cloud-platform

How to query a entity from datastore with Namespace In golang?


I am working on a multi tenant application, I need to query a particular user from a KIND and From Particular Namespace.

I am able to get the values from default Namespace.the package i am using here is "google.golang.org/appengine/datastore"

q := datastore.NewQuery(ENTITYNAME).Filter("Name =", ed.Expense.Name)
    var expenses []ExpenseEntiry
    return q.GetAll(ed.Ctx, &expenses)

Solution

  • The namespace value is not part of the query (it's not a property of the query). The namespace comes from the context which you pass when executing the query, e.g. to Query.GetAll().

    If you have a context (you do as you pass it to q.GetAll()), you can create a derivative context with a given namespace using the appengine.Namespace() function.

    For example:

    ctx2, err := appengine.Namespace(ed.Ctx, "mynamespace")
    // check err
    

    And use this new context to pass to Query.GetAll():

    return q.GetAll(ctx2, &expenses)
    

    It is rare that you need to create a new context with a different namespace, ed.Ctx should already be a context with the right namespace. So when / where you create ed.Ctx, you should already apply the namespace there, so you can avoid "accidental" exposure of data of other tenants (which is a major security issue).