OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package meta |
| 6 |
| 7 import ( |
| 8 "fmt" |
| 9 "strings" |
| 10 |
| 11 "github.com/luci/gae/service/datastore" |
| 12 "golang.org/x/net/context" |
| 13 ) |
| 14 |
| 15 // NamespacesCallback is the callback type used with Namespaces. The callback |
| 16 // will be invoked with each identified namespace. |
| 17 // |
| 18 // If the callback returns an error, iteration will stop. If the error is |
| 19 // datastore.Stop, Namespaces will stop iterating and return nil. Otherwise, |
| 20 // the error will be forwarded. |
| 21 type NamespacesCallback func(string) error |
| 22 |
| 23 // Namespaces returns a list of all of the namespaces in the datastore. |
| 24 // |
| 25 // This is done by issuing a datastore query for kind "__namespace__". The |
| 26 // resulting keys will have IDs for the namespaces, namely: |
| 27 // - The empty namespace will have integer ID 1. This will be forwarded to
the |
| 28 // callback as "". |
| 29 // - Other namespaces will have non-zero string IDs. |
| 30 func Namespaces(c context.Context, cb NamespacesCallback) error { |
| 31 q := datastore.NewQuery("__namespace__").KeysOnly(true) |
| 32 |
| 33 // Query our datastore for the full set of namespaces. |
| 34 return datastore.Get(c).Run(q, func(k *datastore.Key) error { |
| 35 switch { |
| 36 case k.IntID() == 1: |
| 37 return cb("") |
| 38 case k.IntID() != 0: |
| 39 return fmt.Errorf("unexpected namepsace integer key (%d)
", k.IntID()) |
| 40 default: |
| 41 return cb(k.StringID()) |
| 42 } |
| 43 }) |
| 44 } |
| 45 |
| 46 // NamespacesWithPrefix runs Namespaces, returning only namespaces beginning |
| 47 // with the supplied prefix string. |
| 48 func NamespacesWithPrefix(c context.Context, p string, cb NamespacesCallback) er
ror { |
| 49 // TODO: https://github.com/luci/gae/issues/49 : When inequality filters
are |
| 50 // supported, implement this using a "Gte" filter. |
| 51 any := false |
| 52 return Namespaces(c, func(ns string) error { |
| 53 if !strings.HasPrefix(ns, p) { |
| 54 if any { |
| 55 return datastore.Stop |
| 56 } |
| 57 return nil |
| 58 } |
| 59 |
| 60 any = true |
| 61 return cb(ns) |
| 62 }) |
| 63 } |
| 64 |
| 65 // NamespacesCollector exposes a NamespacesCallback function that aggregates |
| 66 // resulting namespaces into the collector slice. |
| 67 type NamespacesCollector []string |
| 68 |
| 69 // Callback is a NamespacesCallback which adds each namespace to the collector. |
| 70 func (c *NamespacesCollector) Callback(v string) error { |
| 71 *c = append(*c, v) |
| 72 return nil |
| 73 } |
OLD | NEW |