1//  Copyright (c) 2014 Couchbase, Inc.
2//  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
3//  except in compliance with the License. You may obtain a copy of the License at
4//    http://www.apache.org/licenses/LICENSE-2.0
5//  Unless required by applicable law or agreed to in writing, software distributed under the
6//  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
7//  either express or implied. See the License for the specific language governing permissions
8//  and limitations under the License.
9
10package algebra
11
12import (
13	"encoding/json"
14
15	"github.com/couchbase/query/errors"
16	"github.com/couchbase/query/expression"
17)
18
19/*
20Represents the keyspace-ref used in DML statements. It
21contains three fields namespace, keyspace (bucket) and
22an alias (as).
23*/
24type KeyspaceRef struct {
25	namespace string `json:"namespace"`
26	keyspace  string `json:"keyspace"`
27	as        string `json:"as"`
28}
29
30/*
31The function NewKeyspaceRef returns a pointer to the
32KeyspaceRef struct by assigning the input attributes
33to the fields of the struct.
34*/
35func NewKeyspaceRef(namespace, keyspace, as string) *KeyspaceRef {
36	return &KeyspaceRef{namespace, keyspace, as}
37}
38
39/*
40Qualify identifiers for the keyspace. It also makes sure that the
41keyspace term contains a name or alias.
42*/
43func (this *KeyspaceRef) Formalize() (f *expression.Formalizer, err error) {
44	keyspace := this.Alias()
45	if keyspace == "" {
46		err = errors.NewNoTermNameError("Keyspace", "plan.keyspace.reference_requires_name_or_alias")
47		return
48	}
49
50	f = expression.NewFormalizer(keyspace, nil)
51	return
52}
53
54/*
55Returns the namespace string.
56*/
57func (this *KeyspaceRef) Namespace() string {
58	return this.namespace
59
60}
61
62/*
63Set the default namespace.
64*/
65func (this *KeyspaceRef) SetDefaultNamespace(namespace string) {
66	if this.namespace == "" {
67		this.namespace = namespace
68	}
69}
70
71/*
72Returns the keyspace string.
73*/
74func (this *KeyspaceRef) Keyspace() string {
75	return this.keyspace
76}
77
78/*
79Returns the AS alias string.
80*/
81func (this *KeyspaceRef) As() string {
82	return this.as
83}
84
85/*
86Returns the alias as the keyspace or the as string
87based on if as is empty.
88*/
89func (this *KeyspaceRef) Alias() string {
90	if this.as != "" {
91		return this.as
92	} else {
93		return this.keyspace
94	}
95}
96
97/*
98Marshals input into byte array.
99*/
100func (this *KeyspaceRef) MarshalJSON() ([]byte, error) {
101	r := make(map[string]interface{}, 3)
102	r["keyspace"] = this.keyspace
103	r["namespace"] = this.namespace
104	if this.as != "" {
105		r["as"] = this.as
106	}
107
108	return json.Marshal(r)
109}
110
111/*
112Returns the full keyspace name, including the namespace.
113*/
114func (this *KeyspaceRef) FullName() string {
115	return this.namespace + ":" + this.keyspace
116}
117