Chromium Code Reviews| Index: service/datastore/meta/namespaces.go |
| diff --git a/service/datastore/meta/namespaces.go b/service/datastore/meta/namespaces.go |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..5fcc8ad539e720e927bad6af1441e881f9b182c9 |
| --- /dev/null |
| +++ b/service/datastore/meta/namespaces.go |
| @@ -0,0 +1,67 @@ |
| +// Copyright 2015 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +package meta |
| + |
| +import ( |
| + "strings" |
| + |
| + "github.com/luci/gae/service/datastore" |
| + "golang.org/x/net/context" |
| +) |
| + |
| +// NamespacesCallback is the callback type used with Namespaces. The callback |
| +// will be invoked with each identified namespace. |
| +// |
| +// If the callback returns an error, iteration will stop. If the error is |
| +// datastore.Stop, Namespaces will stop iterating and return nil. Otherwise, |
| +// the error will be forwarded. |
| +type NamespacesCallback func(string) error |
| + |
| +// Namespaces returns a list of all of the namespaces in the datastore. |
| +// |
| +// This is done by issuing a datastore query for kind "__namespace__". The |
| +// resulting keys will have IDs for the namespaces, namely: |
| +// - The empty namespace will have integer ID 1. We ignore this. |
|
iannucci
2016/04/25 08:05:27
Out of curiosity... why? Why not call cb("")?
dnj
2016/04/25 15:24:17
The thought was that someone enumerating namespace
|
| +// - Other namespaces will have string IDs. |
| +func Namespaces(c context.Context, cb NamespacesCallback) error { |
| + q := datastore.NewQuery("__namespace__").KeysOnly(true) |
| + |
| + // Query our datastore for the full set of namespaces. |
| + return datastore.Get(c).Run(q, func(k *datastore.Key) error { |
| + ns := k.StringID() |
| + if ns == "" { |
| + return nil |
| + } |
| + |
| + return cb(ns) |
| + }) |
| +} |
| + |
| +// NamespacesWithPrefix runs Namespaces, returning only namespaces beginning |
| +// with the supplied prefix string. |
| +func NamespacesWithPrefix(c context.Context, p string, cb NamespacesCallback) error { |
|
iannucci
2016/04/25 08:05:27
TODO: https://github.com/luci/gae/issues/49 : Actu
dnj
2016/04/25 15:24:17
Done.
|
| + any := false |
| + return Namespaces(c, func(ns string) error { |
| + if !strings.HasPrefix(ns, p) { |
| + if any { |
| + return datastore.Stop |
| + } |
| + return nil |
| + } |
| + |
| + any = true |
| + return cb(ns) |
| + }) |
| +} |
| + |
| +// NamespacesCollector exposes a NamespacesCallback function that aggregates |
| +// resulting namespaces into the collector slice. |
| +type NamespacesCollector []string |
| + |
| +// Callback is a NamespacesCallback which adds each namespace to the collector. |
| +func (c *NamespacesCollector) Callback(v string) error { |
| + *c = append(*c, v) |
| + return nil |
| +} |