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 expression
11
12import (
13	"encoding/base64"
14
15	"github.com/couchbase/query/util"
16	"github.com/couchbase/query/value"
17)
18
19///////////////////////////////////////////////////
20//
21// Base64Encode
22//
23///////////////////////////////////////////////////
24
25/*
26This represents the function BASE64_ENCODE(expr). It returns the
27base64-encoding of expr.
28*/
29type Base64Encode struct {
30	UnaryFunctionBase
31}
32
33func NewBase64Encode(operand Expression) Function {
34	rv := &Base64Encode{
35		*NewUnaryFunctionBase("base64_encode", operand),
36	}
37
38	rv.expr = rv
39	return rv
40}
41
42/*
43Visitor pattern.
44*/
45func (this *Base64Encode) Accept(visitor Visitor) (interface{}, error) {
46	return visitor.VisitFunction(this)
47}
48
49func (this *Base64Encode) Type() value.Type { return value.STRING }
50
51func (this *Base64Encode) Evaluate(item value.Value, context Context) (value.Value, error) {
52	return this.UnaryEval(this, item, context)
53}
54
55func (this *Base64Encode) Apply(context Context, arg value.Value) (value.Value, error) {
56	if arg.Type() == value.MISSING {
57		return value.MISSING_VALUE, nil
58	}
59
60	bytes, _ := arg.MarshalJSON() // Ignore errors from BINARY values
61	str := base64.StdEncoding.EncodeToString(bytes)
62	return value.NewValue(str), nil
63}
64
65/*
66Factory method pattern.
67*/
68func (this *Base64Encode) Constructor() FunctionConstructor {
69	return func(operands ...Expression) Function {
70		return NewBase64Encode(operands[0])
71	}
72}
73
74///////////////////////////////////////////////////
75//
76// Base64Decode
77//
78///////////////////////////////////////////////////
79
80/*
81This represents the function BASE64_DECODE(expr). It returns the
82base64-decoding of expr.
83*/
84type Base64Decode struct {
85	UnaryFunctionBase
86}
87
88func NewBase64Decode(operand Expression) Function {
89	rv := &Base64Decode{
90		*NewUnaryFunctionBase("base64_decode", operand),
91	}
92
93	rv.expr = rv
94	return rv
95}
96
97/*
98Visitor pattern.
99*/
100func (this *Base64Decode) Accept(visitor Visitor) (interface{}, error) {
101	return visitor.VisitFunction(this)
102}
103
104func (this *Base64Decode) Type() value.Type { return value.STRING }
105
106func (this *Base64Decode) Evaluate(item value.Value, context Context) (value.Value, error) {
107	return this.UnaryEval(this, item, context)
108}
109
110func (this *Base64Decode) Apply(context Context, arg value.Value) (value.Value, error) {
111	if arg.Type() == value.MISSING {
112		return value.MISSING_VALUE, nil
113	} else if arg.Type() != value.STRING {
114		return value.NULL_VALUE, nil
115	}
116
117	str, err := base64.StdEncoding.DecodeString(arg.Actual().(string))
118	if err != nil {
119		return value.NULL_VALUE, nil
120	} else {
121		return value.NewValue(str), nil
122	}
123}
124
125/*
126Factory method pattern.
127*/
128func (this *Base64Decode) Constructor() FunctionConstructor {
129	return func(operands ...Expression) Function {
130		return NewBase64Decode(operands[0])
131	}
132}
133
134///////////////////////////////////////////////////
135//
136// Meta
137//
138///////////////////////////////////////////////////
139
140/*
141This represents the Meta function META(expr).
142*/
143type Meta struct {
144	FunctionBase
145}
146
147func NewMeta(operands ...Expression) Function {
148	rv := &Meta{
149		*NewFunctionBase("meta", operands...),
150	}
151
152	if len(operands) > 0 {
153		if ident, ok := operands[0].(*Identifier); ok {
154			ident.SetKeyspaceAlias(true)
155		}
156	}
157
158	rv.expr = rv
159	return rv
160}
161
162/*
163Visitor pattern.
164*/
165func (this *Meta) Accept(visitor Visitor) (interface{}, error) {
166	return visitor.VisitFunction(this)
167}
168
169func (this *Meta) Type() value.Type { return value.OBJECT }
170
171func (this *Meta) Evaluate(item value.Value, context Context) (value.Value, error) {
172	val := item
173
174	if len(this.operands) > 0 {
175		arg, err := this.operands[0].Evaluate(item, context)
176		if err != nil {
177			return nil, err
178		}
179
180		val = arg
181	}
182
183	if val.Type() == value.MISSING {
184		return val, nil
185	}
186
187	switch val := val.(type) {
188	case value.AnnotatedValue:
189		return value.NewValue(val.GetAttachment("meta")), nil
190	default:
191		return value.NULL_VALUE, nil
192	}
193}
194
195func (this *Meta) Indexable() bool {
196	return true
197}
198
199func (this *Meta) CoveredBy(keyspace string, exprs Expressions, options CoveredOptions) Covered {
200	if len(this.operands) > 0 {
201		alias := NewIdentifier(keyspace)
202		if !this.operands[0].DependsOn(alias) {
203
204			// MB-22561: skip the rest of the expression if different keyspace
205			return CoveredSkip
206		}
207	}
208
209	for _, expr := range exprs {
210		if this.EquivalentTo(expr) {
211			return CoveredTrue
212		}
213	}
214
215	return CoveredFalse
216}
217
218func (this *Meta) MinArgs() int { return 0 }
219
220func (this *Meta) MaxArgs() int { return 1 }
221
222/*
223Factory method pattern.
224*/
225func (this *Meta) Constructor() FunctionConstructor {
226	return func(operands ...Expression) Function {
227		return NewMeta(operands...)
228	}
229}
230
231///////////////////////////////////////////////////
232//
233// Self
234//
235///////////////////////////////////////////////////
236
237/*
238This represents the Meta function SELF(). It makes the
239result into a valid json value after removing the object
240mapper.
241*/
242type Self struct {
243	NullaryFunctionBase
244}
245
246var SELF = NewSelf()
247
248func NewSelf() Function {
249	rv := &Self{
250		*NewNullaryFunctionBase("self"),
251	}
252
253	rv.expr = rv
254	return rv
255}
256
257/*
258Visitor pattern.
259*/
260func (this *Self) Accept(visitor Visitor) (interface{}, error) {
261	return visitor.VisitSelf(this)
262}
263
264/*
265It returns a JSON value.
266*/
267func (this *Self) Type() value.Type { return value.JSON }
268
269/*
270Returns the input item.
271*/
272func (this *Self) Evaluate(item value.Value, context Context) (value.Value, error) {
273	return item, nil
274}
275
276func (this *Self) Indexable() bool {
277	return true
278}
279
280func (this *Self) CoveredBy(keyspace string, exprs Expressions, options CoveredOptions) Covered {
281	return CoveredFalse
282}
283
284func (this *Self) SurvivesGrouping(groupKeys Expressions, allowed *value.ScopeValue) (
285	bool, Expression) {
286	for _, key := range groupKeys {
287		if this.EquivalentTo(key) {
288			return true, nil
289		}
290	}
291
292	return false, nil
293}
294
295/*
296Factory method pattern.
297*/
298func (this *Self) Constructor() FunctionConstructor {
299	return func(operands ...Expression) Function { return SELF }
300}
301
302///////////////////////////////////////////////////
303//
304// Uuid
305//
306///////////////////////////////////////////////////
307
308/*
309This represents the Meta function UUID(). It returns
310a version 4 Universally Unique Identifier.
311*/
312type Uuid struct {
313	NullaryFunctionBase
314}
315
316func NewUuid() Function {
317	rv := &Uuid{
318		*NewNullaryFunctionBase("uuid"),
319	}
320
321	rv.setVolatile()
322	rv.expr = rv
323	return rv
324}
325
326/*
327Visitor pattern.
328*/
329func (this *Uuid) Accept(visitor Visitor) (interface{}, error) {
330	return visitor.VisitFunction(this)
331}
332
333func (this *Uuid) Type() value.Type { return value.STRING }
334
335/*
336Generate a Version 4 UUID as specified in RFC 4122, wrap it in a value
337and return it. The UUID() function may return an error, if so return
338a nil value UUID with the error.
339*/
340func (this *Uuid) Evaluate(item value.Value, context Context) (value.Value, error) {
341	u, err := util.UUIDV3()
342	if err != nil {
343		return nil, err
344	}
345	return value.NewValue(u), nil
346}
347
348/*
349Factory method pattern.
350*/
351func (this *Uuid) Constructor() FunctionConstructor {
352	return func(operands ...Expression) Function {
353		return NewUuid()
354	}
355}
356
357///////////////////////////////////////////////////
358//
359// Version
360//
361///////////////////////////////////////////////////
362
363/*
364This represents the Meta function VERSION(). It returns
365the current version of N1QL.
366*/
367type Version struct {
368	NullaryFunctionBase
369}
370
371func NewVersion() Function {
372	rv := &Version{
373		*NewNullaryFunctionBase("version"),
374	}
375
376	rv.expr = rv
377	return rv
378}
379
380/*
381Visitor pattern.
382*/
383func (this *Version) Accept(visitor Visitor) (interface{}, error) {
384	return visitor.VisitFunction(this)
385}
386
387func (this *Version) Type() value.Type { return value.STRING }
388
389/*
390Return the current server version, wrapped in a value.
391*/
392func (this *Version) Evaluate(item value.Value, context Context) (value.Value, error) {
393	return _VERSION_VALUE, nil
394}
395
396var _VERSION_VALUE = value.NewValue(util.VERSION)
397
398func (this *Version) Value() value.Value {
399	return _VERSION_VALUE
400}
401
402func (this *Version) Indexable() bool {
403	return false
404}
405
406/*
407Factory method pattern.
408*/
409func (this *Version) Constructor() FunctionConstructor {
410	return func(operands ...Expression) Function {
411		return NewVersion()
412	}
413}
414
415///////////////////////////////////////////////////
416//
417// MinVersion
418//
419///////////////////////////////////////////////////
420
421/*
422This represents the function MIN_VERSION(). It returns
423the current minimum supported version of N1QL.
424*/
425type MinVersion struct {
426	NullaryFunctionBase
427}
428
429func NewMinVersion() Function {
430	rv := &MinVersion{
431		*NewNullaryFunctionBase("min_version"),
432	}
433
434	rv.expr = rv
435	return rv
436}
437
438/*
439Visitor pattern.
440*/
441func (this *MinVersion) Accept(visitor Visitor) (interface{}, error) {
442	return visitor.VisitFunction(this)
443}
444
445func (this *MinVersion) Type() value.Type { return value.STRING }
446
447/*
448Return the current minimum version, wrapped in a value.
449*/
450func (this *MinVersion) Evaluate(item value.Value, context Context) (value.Value, error) {
451	return _MIN_VERSION_VALUE, nil
452}
453
454var _MIN_VERSION_VALUE = value.NewValue(util.MIN_VERSION)
455
456func (this *MinVersion) Value() value.Value {
457	return _MIN_VERSION_VALUE
458}
459
460func (this *MinVersion) Indexable() bool {
461	return false
462}
463
464/*
465Factory method pattern.
466*/
467func (this *MinVersion) Constructor() FunctionConstructor {
468	return func(operands ...Expression) Function {
469		return NewMinVersion()
470	}
471}
472
473///////////////////////////////////////////////////
474//
475// CurrentUsers
476//
477///////////////////////////////////////////////////
478
479/*
480This represents the array function CURRENT_USERS(). It
481returns the authenticated users of the query as an array
482of strings.
483*/
484type CurrentUsers struct {
485	NullaryFunctionBase
486}
487
488func NewCurrentUsers() Function {
489	rv := &CurrentUsers{
490		*NewNullaryFunctionBase("current_users"),
491	}
492
493	rv.expr = rv
494	return rv
495}
496
497/*
498Visitor pattern.
499*/
500func (this *CurrentUsers) Accept(visitor Visitor) (interface{}, error) {
501	return visitor.VisitFunction(this)
502}
503
504func (this *CurrentUsers) Type() value.Type { return value.ARRAY }
505
506func (this *CurrentUsers) Evaluate(item value.Value, context Context) (value.Value, error) {
507	authUsers := context.AuthenticatedUsers()
508	arr := make([]interface{}, len(authUsers))
509	for i, user := range authUsers {
510		arr[i] = user
511	}
512	arrVal := value.NewValue(arr)
513	return arrVal, nil
514}
515
516func (this *CurrentUsers) Static() Expression {
517	return this
518}
519
520/*
521Factory method pattern.
522*/
523func (this *CurrentUsers) Constructor() FunctionConstructor {
524	return func(operands ...Expression) Function { return NewCurrentUsers() }
525}
526
527///////////////////////////////////////////////////
528//
529// DsVersion
530//
531///////////////////////////////////////////////////
532
533/*
534This represents the Meta function DS_VERSION(). It returns
535the current version of the server, a string like "4.7.0-1544-enterprise".
536*/
537type DsVersion struct {
538	NullaryFunctionBase
539}
540
541func NewDsVersion() Function {
542	rv := &DsVersion{
543		*NewNullaryFunctionBase("ds_version"),
544	}
545
546	rv.expr = rv
547	return rv
548}
549
550/*
551Visitor pattern.
552*/
553func (this *DsVersion) Accept(visitor Visitor) (interface{}, error) {
554	return visitor.VisitFunction(this)
555}
556
557func (this *DsVersion) Type() value.Type { return value.STRING }
558
559/*
560Return the current server version, wrapped in a value.
561*/
562func (this *DsVersion) Evaluate(item value.Value, context Context) (value.Value, error) {
563	version := context.DatastoreVersion()
564	return value.NewValue(version), nil
565}
566
567func (this *DsVersion) Indexable() bool {
568	return false
569}
570
571/*
572Factory method pattern.
573*/
574func (this *DsVersion) Constructor() FunctionConstructor {
575	return func(operands ...Expression) Function {
576		return NewDsVersion()
577	}
578}
579