diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 9babcdb9..00000000 --- a/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!app -!surreal \ No newline at end of file diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 476dd162..00000000 --- a/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -# EditorConfig coding styles definitions. For more information about the -# properties used in this file, please see the EditorConfig documentation: -# http://editorconfig.org/ - -root = true - -[*] -charset = utf-8 -end_of_line = LF -indent_size = 4 -indent_style = tab -insert_final_newline = true -trim_trailing_whitespace = true - -[*.{yml,json}] -indent_size = 2 -indent_style = space - -[*.{md,diff}] -trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore deleted file mode 100644 index a7206040..00000000 --- a/.gitignore +++ /dev/null @@ -1,43 +0,0 @@ -# ----------------------------------- -# OS X -# ----------------------------------- - -# Directory files -.DS_Store -.AppleDouble -.LSOverride - -# Thumbnail files -._* - -# Files that might appear on external disk -.Spotlight-V100 -.Trashes - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# ----------------------------------- -# Files -# ----------------------------------- - -*.test -*.cover - -# ----------------------------------- -# Folders -# ----------------------------------- - -app/ -dev/ - -# ----------------------------------- -# Specific -# ----------------------------------- - -surreal -*.db diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 6a0aec37..00000000 --- a/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM alpine:latest - -RUN apk add --update --no-cache ca-certificates - -ADD surreal /usr/bin/ - -ENTRYPOINT ["surreal"] diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 8b50463e..00000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright © 2020 SurrealDB Ltd. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/Makefile b/Makefile deleted file mode 100644 index 35cb7930..00000000 --- a/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright © 2016 SurrealDB Ltd. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -GO ?= CGO_ENABLED=0 go -CGO ?= CGO_ENABLED=1 go -LDF := -s -w - -.PHONY: default -default: - @echo "Choose a Makefile target:" - @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print " - " $$1}}' | sort - -.PHONY: kill -kill: - pkill -9 -f surreal - -.PHONY: clean -clean: - $(GO) clean -i -n - -.PHONY: tests -tests: - $(GO) test ./... - -.PHONY: racer -racer: - $(CGO) test -race ./... - -.PHONY: build -build: LDF += $(shell GOPATH=${GOPATH} build/flags.sh) -build: - $(GO) build -v -ldflags '$(LDF)' - -.PHONY: install -install: LDF += $(shell GOPATH=${GOPATH} build/flags.sh) -install: - $(GO) install -v -ldflags '$(LDF)' - -.PHONY: compile -compile: LDF += $(shell GOPATH=${GOPATH} build/flags.sh) -compile: - GOOS=linux GOARCH=amd64 $(GO) build -v -ldflags '$(LDF)' - docker build --tag surrealdb/surrealdb:latest . - docker push surrealdb/surrealdb:latest - -.PHONY: deploy -deploy: - build/macos.sh - build/linux.sh - build/windows.sh diff --git a/README.md b/README.md deleted file mode 100644 index c9c53794..00000000 --- a/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# Surreal - -Surreal is a scalable, distributed, strongly-consistent, collaborative document-graph database. - -[![](https://img.shields.io/badge/status-alpha-ff00bb.svg?style=flat-square)](https://github.com/surrealdb/surrealdb) [![](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat-square)](https://godoc.org/github.com/surrealdb/surrealdb) [![](https://goreportcard.com/badge/github.com/surrealdb/surrealdb?style=flat-square)](https://goreportcard.com/report/github.com/surrealdb/surrealdb) [![](https://img.shields.io/badge/license-Apache_License_2.0-00bfff.svg?style=flat-square)](https://github.com/surrealdb/surrealdb) - -#### Features - -- NoSQL document-graph database written in [Go](http://golang.org) -- Administrative **database tools** - - Easily import data into a cluster - - Easily export data from a cluster - - Accessible and intuitive web interface -- Multiple **connection methods** - - Connect using REST - - Connect using JSON-RPC - - Connect using Websockets -- Multiple **data querying** methods - - Use advanced SQL queries - - Query using REST url endpoints - - Query using Websocket methods -- Customisable **authentication** access - - Specify public or private access - - Admin access to all database data - - Token access to all database data - - End-user multi-tenancy authentication -- Flexible **data manipulation** queries - - Automatic creation of tables - - Schema-less or schema-full tables - - Automatic data field sanitization - - Mandatory, readonly, and validated data fields - - Define embedded fields, and object arrays -- Advanced customisable **indexing** support - - Single-column indexes - - Multiple-column indexes - - Multiple-compound indexes - - Indexing of embedded data fields - - JS/LUA scripting for custom indexes - - Full-text indexing of all data by default -- **Collaborative** editing and manipulation of data - - Live realtime queries - - Publish data changes - - Subscribe to data changes - - Built-in concurrency control - - Pub/sub over websocket for data updates -- **Encryption** out-of-the-box as standard - - End-to-end intra-cluster communications - - End-user SSL encryption for http endpoints - - Encryption of all data at rest using AES-256 - -#### Installation - -```bash -go get github.com/surrealdb/surrealdb -``` - -#### Running - -```bash -surreal start --port-web 8000 -``` - -#### Clustering - -```bash -surreal start --port-web 8000 --port-tcp 33693 --db-path file://surreal-1.db --join localhost:33693 --log-level debug -surreal start --port-web 8001 --port-tcp 33694 --db-path file://surreal-2.db --join localhost:33693 --log-level debug -surreal start --port-web 8002 --port-tcp 33695 --db-path file://surreal-3.db --join localhost:33693 --log-level debug -``` - -#### Deployment - -```bash -docker run --name surreal-1 abcum/surreal start --port-web 8000 --port-tcp 33693 --join localhost:33693 --log-level debug -docker run --name surreal-2 abcum/surreal start --port-web 8001 --port-tcp 33694 --join localhost:33693 --log-level debug -docker run --name surreal-3 abcum/surreal start --port-web 8002 --port-tcp 33695 --join localhost:33693 --log-level debug -``` diff --git a/build/flags.sh b/build/flags.sh deleted file mode 100755 index cb358f24..00000000 --- a/build/flags.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env sh - -set -eu - -cd "$(dirname "${0}")/.." - -echo '-X "github.com/surrealdb/surrealdb/util/build.rev='$(git rev-parse HEAD)'"' \ - '-X "github.com/surrealdb/surrealdb/util/build.ver='$(git describe --tags --abbrev=0 || echo 0.0.0)'"' \ - '-X "github.com/surrealdb/surrealdb/util/build.time='$(date -u '+%Y/%m/%d %H:%M:%S')'"' diff --git a/build/linux.sh b/build/linux.sh deleted file mode 100755 index d42078b8..00000000 --- a/build/linux.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -VERS=$(git describe --tags --abbrev=0) -NAME=surreal-${VERS}.linux-amd64 -HASH=${NAME}.txt -FILE=${NAME}.tgz - -GOOS=linux GOARCH=amd64 go build -v -ldflags "$(bash build/flags.sh)" -tar -zcvf $FILE -s "#^#${NAME}/#" surreal - -echo $(shasum -a 256 $FILE | cut -f1 -d' ') > $HASH - -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$FILE s3://download.surrealdb.com/ -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$HASH s3://download.surrealdb.com/ - -rm -rf $FILE $HASH surreal.exe surreal diff --git a/build/macos.sh b/build/macos.sh deleted file mode 100755 index c0019b10..00000000 --- a/build/macos.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bash - -VERS=$(git describe --tags --abbrev=0) -NAME=surreal-${VERS}.darwin-universal -HASH=${NAME}.txt -FILE=${NAME}.tgz - -GOOS=darwin GOARCH=amd64 go build -v -o surreal-amd64 -ldflags "$(bash build/flags.sh)" -GOOS=darwin GOARCH=arm64 go build -v -o surreal-arm64 -ldflags "$(bash build/flags.sh)" -lipo -create -output surreal surreal-amd64 surreal-arm64 -tar -zcvf $FILE -s "#^#${NAME}/#" surreal - -echo $(shasum -a 256 $FILE | cut -f1 -d' ') > $HASH - -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$FILE s3://download.surrealdb.com/ -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$HASH s3://download.surrealdb.com/ - -rm -rf $FILE $HASH surreal.exe surreal surreal-amd64 surreal-arm64 - -# amd64 - -NAME=surreal-${VERS}.darwin-amd64 -HASH=${NAME}.txt -FILE=${NAME}.tgz - -GOOS=darwin GOARCH=amd64 go build -v -ldflags "$(bash build/flags.sh)" -tar -zcvf $FILE -s "#^#${NAME}/#" surreal - -echo $(shasum -a 256 $FILE | cut -f1 -d' ') > $HASH - -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$FILE s3://download.surrealdb.com/ -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$HASH s3://download.surrealdb.com/ - -rm -rf $FILE $HASH surreal.exe surreal - -# arm64 - -NAME=surreal-${VERS}.darwin-arm64 -HASH=${NAME}.txt -FILE=${NAME}.tgz - -GOOS=darwin GOARCH=amd64 go build -v -ldflags "$(bash build/flags.sh)" -tar -zcvf $FILE -s "#^#${NAME}/#" surreal - -echo $(shasum -a 256 $FILE | cut -f1 -d' ') > $HASH - -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$FILE s3://download.surrealdb.com/ -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$HASH s3://download.surrealdb.com/ - -rm -rf $FILE $HASH surreal.exe surreal diff --git a/build/windows.sh b/build/windows.sh deleted file mode 100755 index 9e04ac48..00000000 --- a/build/windows.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -VERS=$(git describe --tags --abbrev=0) -NAME=surreal-${VERS}.windows-amd64 -HASH=${NAME}.txt -FILE=${NAME}.tgz - -GOOS=windows GOARCH=amd64 go build -v -ldflags "$(bash build/flags.sh)" -tar -zcvf $FILE -s "#^#${NAME}/#" surreal.exe - -echo $(shasum -a 256 $FILE | cut -f1 -d' ') > $HASH - -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$FILE s3://download.surrealdb.com/ -aws s3 cp --region eu-west-2 --cache-control "no-store" ./$HASH s3://download.surrealdb.com/ - -rm -rf $FILE $HASH surreal.exe surreal diff --git a/cli/cli.go b/cli/cli.go deleted file mode 100644 index ecd722f4..00000000 --- a/cli/cli.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "os" - - "github.com/spf13/cobra" - - "github.com/surrealdb/surrealdb/cnf" -) - -var opts *cnf.Options - -var mainCmd = &cobra.Command{ - Use: "surreal", - Short: "SurrealDB command-line interface and server", -} - -func init() { - - mainCmd.AddCommand( - startCmd, - importCmd, - exportCmd, - versionCmd, - ) - - opts = &cnf.Options{} - - mainCmd.PersistentFlags().StringVar(&opts.Logging.Level, "log-level", "error", "Specify log verbosity") - mainCmd.PersistentFlags().StringVar(&opts.Logging.Output, "log-output", "stderr", "Specify log output destination") - mainCmd.PersistentFlags().StringVar(&opts.Logging.Format, "log-format", "text", "Specify log output format (text, json)") - - cobra.OnInitialize(setup) - -} - -// Init runs the cli app -func Init() { - if err := mainCmd.Execute(); err != nil { - os.Exit(1) - } -} diff --git a/cli/export.go b/cli/export.go deleted file mode 100644 index 4a2a27f8..00000000 --- a/cli/export.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "fmt" - "io" - "net/http" - "os" - - "io/ioutil" - - "github.com/spf13/cobra" - - "github.com/surrealdb/surrealdb/log" -) - -var ( - exportUser string - exportPass string - exportConn string - exportNS string - exportDB string -) - -var exportCmd = &cobra.Command{ - Use: "export [flags] ", - Short: "Export an existing database into a SQL script", - Example: " surreal export --auth root:root backup.sql", - RunE: func(cmd *cobra.Command, args []string) (err error) { - - var fle *os.File - var req *http.Request - var res *http.Response - - // Ensure that the command has a filepath - // as the output file argument. If no filepath - // has been provided then return an error. - - if len(args) != 1 { - log.Fatalln("No filepath provided.") - return - } - - // Attempt to open or create the specified file - // in write-only mode, and if there is a problem - // creating the file, then return an error. - - if fle, err = os.OpenFile(args[0], os.O_CREATE|os.O_WRONLY, 0644); err != nil { - log.Fatalln("Export failed - please check the filepath and try again.") - return - } - - defer fle.Close() - - // Create a new http request object that we - // can use to connect to the export endpoint - // using a GET http request type. - - url := fmt.Sprintf("%s/export", exportConn) - - if req, err = http.NewRequest("GET", url, nil); err != nil { - log.Fatalln("Connection failed - check the connection details and try again.") - return - } - - // Specify that the request is an octet stream - - req.Header.Set("Content-Type", "application/octet-stream") - - // Specify the db authentication settings - - req.SetBasicAuth(exportUser, exportPass) - - // Specify the namespace to export - - req.Header.Set("NS", exportNS) - - // Specify the database to export - - req.Header.Set("DB", exportDB) - - // Attempt to dial the export endpoint and - // if there is an error then stop execution - // and return the connection error. - - if res, err = http.DefaultClient.Do(req); err != nil { - log.Fatalln("Connection failed - check the connection details and try again.") - return - } - - // Ensure that we close the body, otherwise - // if the Body is not closed, the Client can - // not use the underlying transport again. - - defer res.Body.Close() - - // Ensure that we didn't receive a 401 status - // code back from the server, otherwise there - // was a problem with our authentication. - - if res.StatusCode == 401 { - log.Fatalln("Authentication failed - check the connection details and try again.") - return - } - - // Ensure that we received a http 200 status - // code back from the server, otherwise there - // was a problem with our request. - - if res.StatusCode != 200 { - bdy, _ := ioutil.ReadAll(res.Body) - log.Fatalf("%s", bdy) - return - } - - // Copy the http response body to stdOut so - // that we can pipe the response to other - // commands or processes. - - if _, err = io.Copy(fle, res.Body); err != nil { - log.Fatalln("Export failed - there was an error saving the database content.") - return - } - - return - - }, -} - -func init() { - - exportCmd.PersistentFlags().StringVarP(&exportUser, "user", "u", "root", "Database authentication username to use when connecting.") - exportCmd.PersistentFlags().StringVarP(&exportPass, "pass", "p", "pass", "Database authentication password to use when connecting.") - exportCmd.PersistentFlags().StringVarP(&exportConn, "conn", "c", "https://surreal.io", "Remote database server url to connect to.") - exportCmd.PersistentFlags().StringVar(&exportNS, "ns", "", "Master authentication details to use when connecting.") - exportCmd.PersistentFlags().StringVar(&exportDB, "db", "", "Master authentication details to use when connecting.") - -} diff --git a/cli/import.go b/cli/import.go deleted file mode 100644 index 8502e625..00000000 --- a/cli/import.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "fmt" - "net/http" - "os" - - "io/ioutil" - - "github.com/spf13/cobra" - - "github.com/surrealdb/surrealdb/log" -) - -var ( - importUser string - importPass string - importConn string - importNS string - importDB string -) - -var importCmd = &cobra.Command{ - Use: "import [flags] ", - Short: "Import a SQL script into an existing database", - Example: " surreal import --auth root:root backup.sql", - RunE: func(cmd *cobra.Command, args []string) (err error) { - - var fle *os.File - var req *http.Request - var res *http.Response - - // Ensure that the command has a filepath - // as the output file argument. If no filepath - // has been provided then return an error. - - if len(args) != 1 { - log.Fatalln("No filepath provided.") - return - } - - // Attempt to open or create the specified file - // in write-only mode, and if there is a problem - // creating the file, then return an error. - - if fle, err = os.OpenFile(args[0], os.O_RDONLY, 0644); err != nil { - log.Fatalln("SQL failed - please check the filepath and try again.") - return - } - - defer fle.Close() - - // Configure the sql connection endpoint url - // and specify the authentication header using - // basic auth for root login. - - url := fmt.Sprintf("%s/sql", importConn) - - if req, err = http.NewRequest("POST", url, fle); err != nil { - log.Fatalln("Connection failed - check the connection details and try again.") - return - } - - // Specify that the request is plain text - - req.Header.Set("Content-Type", "text/plain") - - // Specify the db authentication settings - - req.SetBasicAuth(importUser, importPass) - - // Specify the namespace to import - - req.Header.Set("NS", importNS) - - // Specify the database to import - - req.Header.Set("DB", importDB) - - // Attempt to dial the sql endpoint and - // if there is an error then stop execution - // and return the connection error. - - if res, err = http.DefaultClient.Do(req); err != nil { - log.Fatalln("Connection failed - check the connection details and try again.") - return - } - - // Ensure that we close the body, otherwise - // if the Body is not closed, the Client can - // not use the underlying transport again. - - defer res.Body.Close() - - // Ensure that we didn't receive a 401 status - // code back from the server, otherwise there - // was a problem with our authentication. - - if res.StatusCode == 401 { - log.Fatalln("Authentication failed - check the connection details and try again.") - return - } - - // Ensure that we received a http 200 status - // code back from the server, otherwise there - // was a problem with our request. - - if res.StatusCode != 200 { - bdy, _ := ioutil.ReadAll(res.Body) - log.Fatalf("%s", bdy) - return - } - - return - - }, -} - -func init() { - - importCmd.PersistentFlags().StringVarP(&importUser, "user", "u", "root", "Database authentication username to use when connecting.") - importCmd.PersistentFlags().StringVarP(&importPass, "pass", "p", "pass", "Database authentication password to use when connecting.") - importCmd.PersistentFlags().StringVarP(&importConn, "conn", "c", "https://surreal.io", "Remote database server url to connect to.") - importCmd.PersistentFlags().StringVar(&importNS, "ns", "", "Master authentication details to use when connecting.") - importCmd.PersistentFlags().StringVar(&importDB, "db", "", "Master authentication details to use when connecting.") - -} diff --git a/cli/logo.go b/cli/logo.go deleted file mode 100644 index c02d850a..00000000 --- a/cli/logo.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -const logo = ` - .d8888b. 888 8888888b. 888888b. -d88P Y88b 888 888 "Y88b 888 "88b -Y88b. 888 888 888 888 .88P - "Y888b. 888 888 888d888 888d888 .d88b. 8888b. 888 888 888 8888888K. - "Y88b. 888 888 888P" 888P" d8P Y8b "88b 888 888 888 888 "Y88b - "888 888 888 888 888 88888888 .d888888 888 888 888 888 888 -Y88b d88P Y88b 888 888 888 Y8b. 888 888 888 888 .d88P 888 d88P - "Y8888P" "Y88888 888 888 "Y8888 "Y888888 888 8888888P" 8888888P" - -` diff --git a/cli/setup.go b/cli/setup.go deleted file mode 100644 index f03589ff..00000000 --- a/cli/setup.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "fmt" - "net" - "os" - "path" - "regexp" - "strings" - - "encoding/pem" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/log" - "github.com/surrealdb/surrealdb/util/rand" -) - -func setup() { - - // -------------------------------------------------- - // DB - // -------------------------------------------------- - - // Ensure that the default - // database options are set - - if opts.DB.Path == "" { - opts.DB.Path = "memory" - } - - if opts.DB.Base == "" { - opts.DB.Base = "surreal" - } - - if opts.DB.Code != "" { - opts.DB.Key = []byte(opts.DB.Code) - } - - switch len(opts.DB.Key) { - case 0, 16, 24, 32: - default: - log.Fatal("Specify a valid encryption key length. Valid key sizes are 16bit, 24bit, or 32bit.") - } - - if opts.DB.Path != "memory" { - if ok, _ := regexp.MatchString(`^(file|dendrodb)://(.+)$`, opts.DB.Path); !ok { - log.Fatalf("Invalid path %s. Specify a valid data store configuration path", opts.DB.Path) - } - } - - if opts.DB.Cert.CA != "" || opts.DB.Cert.Crt != "" || opts.DB.Cert.Key != "" { - - opts.DB.Cert.SSL = true - - if dec, _ := pem.Decode([]byte(opts.DB.Cert.CA)); dec == nil || dec.Type != "CERTIFICATE" { - log.Fatal("Specify a valid PEM encoded CA file.") - } - - if dec, _ := pem.Decode([]byte(opts.DB.Cert.Crt)); dec == nil || dec.Type != "CERTIFICATE" { - log.Fatal("Specify a valid PEM encoded certificate file.") - } - - if dec, _ := pem.Decode([]byte(opts.DB.Cert.Key)); dec == nil || dec.Type != "RSA PRIVATE KEY" { - log.Fatal("Specify a valid PEM encoded private key file.") - } - - } - - // -------------------------------------------------- - // Ports - // -------------------------------------------------- - - // Specify default port - if opts.Port == 0 { - opts.Port = 8000 - } - - // Specift default host - if opts.Bind == "" { - opts.Bind = "0.0.0.0" - } - - // Ensure port number is valid - if opts.Port < 0 || opts.Port > 65535 { - log.Fatalf("Invalid port %d. Please specify a valid port number for --port-web", opts.Port) - } - - // Store the ports in host:port string format - opts.Conn = fmt.Sprintf("%s:%d", opts.Bind, opts.Port) - - // -------------------------------------------------- - // Auth - // -------------------------------------------------- - - if opts.Auth.Auth != "" { - - if opts.Auth.User != "" { - log.Fatal("Specify only --auth or --auth-user") - } - - if opts.Auth.Pass != "" { - log.Fatal("Specify only --auth or --auth-pass") - } - - both := strings.SplitN(opts.Auth.Auth, ":", 2) - - if len(both) == 2 { - opts.Auth.User = both[0] - opts.Auth.Pass = both[1] - } - - } - - // Ensure that security - // is enabled by default - - if opts.Auth.User == "" { - opts.Auth.User = "root" - } - - if opts.Auth.Pass == "" { - opts.Auth.Pass = string(rand.New(20)) - } - - // Ensure that login as - // root can only be from - // specified ip addresses - - for _, cidr := range opts.Auth.Addr { - _, subn, err := net.ParseCIDR(cidr) - if err != nil { - log.Fatalf("Invalid cidr %s. Please specify a valid CIDR address for --auth-addr", cidr) - } - opts.Auth.Nets = append(opts.Auth.Nets, subn) - } - - // -------------------------------------------------- - // Certs - // -------------------------------------------------- - - if strings.HasPrefix(opts.Cert.Crt, "-----") { - var err error - var doc *os.File - var out string = path.Join(os.TempDir(), "surreal.crt") - if doc, err = os.Create(out); err != nil { - log.Fatalf("Can not decode PEM encoded certificate into %s", out) - } - doc.Write([]byte(opts.Cert.Crt)) - doc.Close() - opts.Cert.Crt = out - } - - if strings.HasPrefix(opts.Cert.Key, "-----") { - var err error - var doc *os.File - var out string = path.Join(os.TempDir(), "surreal.key") - if doc, err = os.Create(out); err != nil { - log.Fatalf("Can not decode PEM encoded private key into %s", out) - } - doc.Write([]byte(opts.Cert.Key)) - doc.Close() - opts.Cert.Key = out - } - - // -------------------------------------------------- - // Logging - // -------------------------------------------------- - - var chk map[string]bool - - // Ensure that the specified - // logging level is allowed - - if opts.Logging.Level != "" { - - chk = map[string]bool{ - "trace": true, - "debug": true, - "info": true, - "warn": true, - "error": true, - "fatal": true, - "panic": true, - } - - if _, ok := chk[opts.Logging.Level]; !ok { - log.Fatal("Incorrect log level specified") - } - - log.SetLevel(opts.Logging.Level) - - } - - // Ensure that the specified - // logging format is allowed - - if opts.Logging.Format != "" { - - chk = map[string]bool{ - "text": true, - "json": true, - } - - if _, ok := chk[opts.Logging.Format]; !ok { - log.Fatal("Incorrect log format specified") - } - - log.SetFormat(opts.Logging.Format) - - } - - // Ensure that the specified - // logging output is allowed - - if opts.Logging.Output != "" { - - chk = map[string]bool{ - "none": true, - "stdout": true, - "stderr": true, - "stackdriver": true, - } - - if _, ok := chk[opts.Logging.Output]; !ok { - log.Fatal("Incorrect log output specified") - } - - log.SetOutput(opts.Logging.Output) - - } - - // Enable global options object - - cnf.Settings = opts - -} diff --git a/cli/start.go b/cli/start.go deleted file mode 100644 index 544068bf..00000000 --- a/cli/start.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "github.com/spf13/cobra" - - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/log" - "github.com/surrealdb/surrealdb/web" -) - -var startCmd = &cobra.Command{ - Use: "start [flags]", - Short: "Start the database and http server", - PreRun: func(cmd *cobra.Command, args []string) { - log.Display(logo) - }, - RunE: func(cmd *cobra.Command, args []string) (err error) { - - if err = kvs.Setup(opts); err != nil { - log.Fatal(err) - return - } - - if err = db.Setup(opts); err != nil { - log.Fatal(err) - return - } - - if err = web.Setup(opts); err != nil { - log.Fatal(err) - return - } - - return - - }, - PostRunE: func(cmd *cobra.Command, args []string) (err error) { - - if err = web.Exit(opts); err != nil { - log.Fatal(err) - return - } - - if err = db.Exit(opts); err != nil { - log.Fatal(err) - return - } - - if err = kvs.Exit(opts); err != nil { - log.Fatal(err) - return - } - - return - - }, -} - -func init() { - - startCmd.PersistentFlags().StringVarP(&opts.Auth.Auth, "auth", "a", "root:root", "Master database authentication details") - startCmd.PersistentFlags().StringVar(&opts.Auth.User, "auth-user", "", "The master username for the database. Use this as an alternative to the --auth flag") - startCmd.PersistentFlags().StringVar(&opts.Auth.Pass, "auth-pass", "", "The master password for the database. Use this as an alternative to the --auth flag") - startCmd.PersistentFlags().StringSliceVar(&opts.Auth.Addr, "auth-addr", []string{"0.0.0.0/0", "0:0:0:0:0:0:0:0/0"}, "The IP address ranges from which master authentication is possible") - - startCmd.PersistentFlags().StringVar(&opts.DB.Path, "path", "", "Database path used for storing data") - startCmd.PersistentFlags().IntVar(&opts.Port, "port", 8000, "The port on which to serve the web server") - startCmd.PersistentFlags().StringVarP(&opts.Bind, "bind", "b", "0.0.0.0", "The hostname or ip address to listen for connections on") - - startCmd.PersistentFlags().DurationVar(&opts.Query.Timeout, "timeout", 0, "") - - startCmd.PersistentFlags().StringVarP(&opts.DB.Code, "key", "k", "", "Encryption key to use for on-disk encryption") - - startCmd.PersistentFlags().DurationVar(&opts.DB.Proc.Flush, "db-flush", 0, "A time duration to use when syncing data to persistent storage") - startCmd.PersistentFlags().DurationVar(&opts.DB.Proc.Shrink, "db-shrink", 0, "A time duration to use when shrinking data on persistent storage") - - startCmd.PersistentFlags().StringVar(&opts.DB.Cert.CA, "kvs-ca", "", "Path to the CA file used to connect to the remote database") - startCmd.PersistentFlags().StringVar(&opts.DB.Cert.Crt, "kvs-crt", "", "Path to the certificate file used to connect to the remote database") - startCmd.PersistentFlags().StringVar(&opts.DB.Cert.Key, "kvs-key", "", "Path to the private key file used to connect to the remote database") - - startCmd.PersistentFlags().StringVar(&opts.Cert.Crt, "web-crt", "", "Path to the server certificate. Needed when running in secure mode") - startCmd.PersistentFlags().StringVar(&opts.Cert.Key, "web-key", "", "Path to the server private key. Needed when running in secure mode") - -} diff --git a/cli/version.go b/cli/version.go deleted file mode 100644 index 7c272cff..00000000 --- a/cli/version.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "fmt" - "os" - "text/tabwriter" - - "github.com/spf13/cobra" - - "github.com/surrealdb/surrealdb/util/build" -) - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Output version information", - Run: func(cmd *cobra.Command, args []string) { - - info := build.GetInfo() - - tw := tabwriter.NewWriter(os.Stdout, 2, 1, 2, ' ', 0) - fmt.Fprintf(tw, "Build Go: %s\n", info.Go) - fmt.Fprintf(tw, "Build Ver: %s\n", info.Ver) - fmt.Fprintf(tw, "Build Rev: %s\n", info.Rev) - fmt.Fprintf(tw, "Build Time: %s\n", info.Time) - - tw.Flush() - - }, -} diff --git a/cnf/auth.go b/cnf/auth.go deleted file mode 100644 index 2861a90a..00000000 --- a/cnf/auth.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cnf - -type Auth struct { - Data interface{} `json:"id" msgpack:"id"` - Kind Kind `json:"-" msgpack:"-"` - Scope string `json:"-" msgpack:"-"` - NS string `json:"-" msgpack:"-"` - DB string `json:"-" msgpack:"-"` -} - -// Reset resets the authentication data. -func (a *Auth) Reset() *Auth { - - // Reset the authentication level - a.Kind = AuthNO - - // Remove any saved session data - a.Data = nil - - // Clear any authenticated scope - a.Scope = "" - - return a - -} diff --git a/cnf/cnf.go b/cnf/cnf.go deleted file mode 100644 index b2f5a2a5..00000000 --- a/cnf/cnf.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cnf - -import ( - "net" - "time" -) - -var Settings *Options - -// Options defines global configuration options -type Options struct { - DB struct { - Key []byte // Data encryption key - Code string // Data encryption key string - Path string // Path to store the data file - Base string // Base key to use in KV stores - Proc struct { - Flush time.Duration // Timeframe for flushing data - Shrink time.Duration // Timeframe for shrinking data - } - Cert struct { - CA string - Crt string - Key string - SSL bool - } - } - - Port int // Port as an number - - Conn string // Port as a string - - Bind string // Hostname of the node - - Cert struct { - Crt string // File location of server crt - Key string // File location of server key - } - - Auth struct { - Auth string // Master authentication user:pass - User string // Master authentication username - Pass string // Master authentication password - Addr []string // Allowed ip ranges for authentication - Nets []*net.IPNet // Allowed cidr ranges for authentication - } - - Query struct { - Timeout time.Duration // Fixed query timeout - } - - Logging struct { - Level string // Stores the configured logging level - Output string // Stores the configured logging output - Format string // Stores the configured logging format - } -} diff --git a/cnf/kind.go b/cnf/kind.go deleted file mode 100644 index 338a6942..00000000 --- a/cnf/kind.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cnf - -const ( - // Root access - AuthKV Kind = iota - // Namespace access - AuthNS - // Database access - AuthDB - // Scoped user access - AuthSC - // No access - AuthNO -) - -type Kind int - -func (k Kind) String() string { - switch k { - default: - return "NO" - case AuthKV: - return "KV" - case AuthNS: - return "NS" - case AuthDB: - return "DB" - case AuthSC: - return "SC" - } -} - -func (k Kind) MarshalText() (data []byte, err error) { - return []byte(k.String()), err -} - -func (k Kind) UnmarshalText(text []byte) error { - return nil -} diff --git a/db/access.go b/db/access.go deleted file mode 100644 index 9747bfcc..00000000 --- a/db/access.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" -) - -func (e *executor) access(ctx context.Context, kind cnf.Kind) (err error) { - - if perm(ctx) > kind { - return new(QueryError) - } - - if kind > cnf.AuthKV && len(e.ns) == 0 { - return new(BlankError) - } - - if kind > cnf.AuthNS && len(e.db) == 0 { - return new(BlankError) - } - - return - -} diff --git a/db/cache.go b/db/cache.go deleted file mode 100644 index 754fb5c5..00000000 --- a/db/cache.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "github.com/dgraph-io/ristretto" -) - -var keyCache *ristretto.Cache -var valCache *ristretto.Cache - -func init() { - - keyCache, _ = ristretto.NewCache(&ristretto.Config{ - NumCounters: 1e7, - MaxCost: 1 << 32, - BufferItems: 64, - Cost: func(i interface{}) int64 { - switch v := i.(type) { - case string: - return int64(len(v)) - case []byte: - return int64(len(v)) - default: - return 1 - } - }, - }) - - valCache, _ = ristretto.NewCache(&ristretto.Config{ - NumCounters: 1e7, - MaxCost: 1 << 32, - BufferItems: 64, - Cost: func(i interface{}) int64 { - switch v := i.(type) { - case string: - return int64(len(v)) - case []byte: - return int64(len(v)) - default: - return 1 - } - }, - }) - -} diff --git a/db/check.go b/db/check.go deleted file mode 100644 index 96f7980c..00000000 --- a/db/check.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" -) - -func (d *document) check(ctx context.Context, cond sql.Expr) (ok bool, err error) { - - // If no condition expression has been - // defined then we can ignore this, and - // process the current document. - - if cond == nil { - return true, nil - } - - // If a condition expression has been - // defined then let's process it to see - // what value it returns or error. - - val, err := d.i.e.fetch(ctx, cond, d.current) - - // If the condition expression result is - // not a boolean value, then let's see - // if the value can be equated to a bool. - - return calcAsBool(val), err - -} - -// Grant checks to see if the table permissions allow -// this record to be accessed for live queries, and -// if not then it errors accordingly. -func (d *document) grant(ctx context.Context, met method) (ok bool, err error) { - - var val interface{} - - // If this is a document loaded from - // a subquery or data param, and not - // from the KV store, then there is - // no need to check permissions. - - if d.key == nil { - return true, nil - } - - // If we are authenticated using DB, NS, - // or KV permissions level, then we can - // ignore all permissions checks, but we - // must ensure the TB, DB, and NS exist. - - if perm(ctx) < cnf.AuthSC { - return true, nil - } - - // Otherwise, get the table definition - // so we can check if the permissions - // allow us to view this document. - - tb, err := d.i.e.tx.GetTB(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return false, err - } - - // Once we have the table we reset the - // context to DB level so that no other - // embedded permissions are checked on - // records within these permissions. - - ctx = context.WithValue(ctx, ctxKeyKind, cnf.AuthDB) - - // We then try to process the relevant - // permissions dependent on the query - // that we are currently processing. If - // there are no permissions specified - // for this table, then because this is - // a scoped request, return an error. - - if p, ok := tb.Perms.(*sql.PermExpression); ok { - switch met { - case _SELECT: - val, err = d.i.e.fetch(ctx, p.Select, d.current) - case _CREATE: - val, err = d.i.e.fetch(ctx, p.Select, d.current) - case _UPDATE: - val, err = d.i.e.fetch(ctx, p.Select, d.current) - case _DELETE: - val, err = d.i.e.fetch(ctx, p.Select, d.initial) - } - } - - // If the permissions expressions - // returns a boolean value, then we - // return this, dictating whether the - // document is able to be viewed. - - return calcAsBool(val), err - -} - -// Query checks to see if the table permissions allow -// this record to be accessed for normal queries, and -// if not then it errors accordingly. -func (d *document) allow(ctx context.Context, met method) (ok bool, err error) { - - var val interface{} - - // If this is a document loaded from - // a subquery or data param, and not - // from the KV store, then there is - // no need to check permissions. - - if d.key == nil { - return true, nil - } - - // If we are authenticated using DB, NS, - // or KV permissions level, then we can - // ignore all permissions checks, but we - // must ensure the TB, DB, and NS exist. - - if perm(ctx) < cnf.AuthSC { - return true, nil - } - - // If this document is being created - // for the first time, then allow this - // check, and recheck after the fields - // have been merged into the document. - - if met == _CREATE && !d.current.Exists("id") { - return true, nil - } - - // Otherwise, get the table definition - // so we can check if the permissions - // allow us to view this document. - - tb, err := d.i.e.tx.GetTB(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return false, err - } - - // Once we have the table we reset the - // context to DB level so that no other - // embedded permissions are checked on - // records within these permissions. - - ctx = context.WithValue(ctx, ctxKeyKind, cnf.AuthDB) - - // We then try to process the relevant - // permissions dependent on the query - // that we are currently processing. If - // there are no permissions specified - // for this table, then because this is - // a scoped request, return an error. - - if p, ok := tb.Perms.(*sql.PermExpression); ok { - switch met { - case _SELECT: - val, err = d.i.e.fetch(ctx, p.Select, d.current) - case _CREATE: - val, err = d.i.e.fetch(ctx, p.Create, d.current) - case _UPDATE: - val, err = d.i.e.fetch(ctx, p.Update, d.current) - case _DELETE: - val, err = d.i.e.fetch(ctx, p.Delete, d.current) - } - } - - // If the permissions expressions - // returns a boolean value, then we - // return this, dictating whether the - // document is able to be viewed. - - return calcAsBool(val), err - -} diff --git a/db/context.go b/db/context.go deleted file mode 100644 index ca0384e4..00000000 --- a/db/context.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" -) - -func vers(ctx context.Context) uint32 { - - v := ctx.Value(ctxKeyDive) - - switch v { - case nil: - return 0 - default: - return v.(uint32) - } - -} - -func perm(ctx context.Context) cnf.Kind { - - v := ctx.Value(ctxKeyKind) - - switch v { - case nil: - return cnf.AuthNO - default: - return v.(cnf.Kind) - } - -} - -func dive(ctx context.Context) context.Context { - - v := ctx.Value(ctxKeyDive) - - switch v { - case nil: - return context.WithValue(ctx, ctxKeyDive, uint32(1)) - default: - if v.(uint32) > maxRecursiveQueries { - panic(errRecursiveOverload) - } - return context.WithValue(ctx, ctxKeyDive, v.(uint32)+1) - } - -} diff --git a/db/create.go b/db/create.go deleted file mode 100644 index 98a46ee0..00000000 --- a/db/create.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/guid" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeCreate(ctx context.Context, stm *sql.CreateStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - var what sql.Exprs - - for _, val := range stm.What { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - what = append(what, w) - } - - i := newIterator(e, ctx, stm, false) - - for _, w := range what { - - switch what := w.(type) { - - default: - return nil, fmt.Errorf("Can not execute CREATE query using value '%v'", what) - - case *sql.Table: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: guid.New().String()} - i.processThing(ctx, key) - - case *sql.Ident: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.VA, ID: guid.New().String()} - i.processThing(ctx, key) - - case *sql.Thing: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: what.ID} - i.processThing(ctx, key) - - case *sql.Model: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processModel(ctx, key, what) - - case *sql.Batch: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processBatch(ctx, key, what) - - // Result of subquery - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, what) - - // Result of subquery with LIMIT 1 - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, []interface{}{what}) - - } - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchCreate(ctx context.Context, stm *sql.CreateStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeCreate(ctx, stm) - if err != nil { - return nil, err - } - - switch len(out) { - case 1: - return data.Consume(out).Get(docKeyOne, docKeyId).Data(), nil - default: - return data.Consume(out).Get(docKeyAll, docKeyId).Data(), nil - } - -} - -func (d *document) runCreate(ctx context.Context, stm *sql.CreateStatement) (interface{}, error) { - - var ok bool - var err error - var met = _CREATE - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.lock(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.val.Exi() == true { - return nil, &ExistError{exist: d.id} - } - - if err = d.merge(ctx, met, stm.Data); err != nil { - return nil, err - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.storeIndex(ctx); err != nil { - return nil, err - } - - if err = d.storeThing(ctx); err != nil { - return nil, err - } - - if err = d.table(ctx, met); err != nil { - return nil, err - } - - if err = d.lives(ctx, met); err != nil { - return nil, err - } - - if err = d.event(ctx, met); err != nil { - return nil, err - } - - return d.yield(ctx, stm, stm.Echo) - -} diff --git a/db/create_test.go b/db/create_test.go deleted file mode 100644 index 92d8d244..00000000 --- a/db/create_test.go +++ /dev/null @@ -1,334 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestCreate(t *testing.T) { - - Convey("Create with invalid value", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE 1; - CREATE "one"; - CREATE ["many"]; - CREATE [{value:"one"}]; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "ERR") - So(res[1].Detail, ShouldEqual, "Can not execute CREATE query using value '1'") - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Can not execute CREATE query using value 'one'") - So(res[3].Status, ShouldEqual, "ERR") - So(res[3].Detail, ShouldEqual, "Can not execute CREATE query using value '[many]'") - So(res[4].Status, ShouldEqual, "ERR") - So(res[4].Detail, ShouldEqual, "Can not execute CREATE query using value '[map[value:one]]'") - - }) - - Convey("Create record when it exists", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - CREATE person:test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 0) - So(res[2].Status, ShouldEqual, "ERR_EX") - So(res[2].Detail, ShouldEqual, "Database record 'person:test' already exists") - - }) - - Convey("Create unique record using `table`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(data.Consume(res[1].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - - }) - - Convey("Create specific record using `thing`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 4) - So(data.Consume(res[1].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - - }) - - Convey("Create unique records using `batch`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE batch("person", ["1", "2", "person:3"]); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[1].Result[2]).Get("meta.id").Data(), ShouldEqual, 3) - - }) - - Convey("Create unique records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:100|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 100) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(data.Consume(res[1].Result[99]).Get("meta.id").Data(), ShouldHaveLength, 20) - - }) - - Convey("Create sequential ascending records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..100|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 100) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[1].Result[99]).Get("meta.id").Data(), ShouldEqual, 100) - - }) - - Convey("Create sequential descending records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:100..1|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 100) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 100) - So(data.Consume(res[1].Result[99]).Get("meta.id").Data(), ShouldEqual, 1) - - }) - - Convey("Create sequential ascending negative-to-positive records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:-50..50|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 101) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, -50) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, -49) - So(data.Consume(res[1].Result[100]).Get("meta.id").Data(), ShouldEqual, 50) - - }) - - Convey("Create sequential ascending decimal records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1,0.5..50|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 99) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, 1.5) - So(data.Consume(res[1].Result[98]).Get("meta.id").Data(), ShouldEqual, 50) - - }) - - Convey("Create sequential descending decimal records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:50,0.5..1|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 99) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 50) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, 49.5) - So(data.Consume(res[1].Result[98]).Get("meta.id").Data(), ShouldEqual, 1) - - }) - - Convey("Create sequential ascending decimal negative-to-positive records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:-50,0.5..50|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 201) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, -50) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, -49.5) - So(data.Consume(res[1].Result[200]).Get("meta.id").Data(), ShouldEqual, 50) - - }) - - Convey("Parsing same ID using ints, floats, and strings", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1; - CREATE person:1.0; - CREATE person:1.0000; - CREATE person:⟨1⟩; - CREATE person:⟨1.0⟩; - CREATE person:⟨1.0000⟩; - SELECT id FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "ERR_EX") - So(res[2].Detail, ShouldEqual, "Database record 'person:1' already exists") - So(res[3].Status, ShouldEqual, "ERR_EX") - So(res[3].Detail, ShouldEqual, "Database record 'person:1' already exists") - So(res[4].Status, ShouldEqual, "ERR_EX") - So(res[4].Detail, ShouldEqual, "Database record 'person:1' already exists") - So(res[5].Status, ShouldEqual, "ERR_EX") - So(res[5].Detail, ShouldEqual, "Database record 'person:1' already exists") - So(res[6].Status, ShouldEqual, "ERR_EX") - So(res[6].Detail, ShouldEqual, "Database record 'person:1' already exists") - So(res[7].Result, ShouldHaveLength, 1) - - }) - - Convey("Creating with a timeout of 1ms returns an error", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..1000| TIMEOUT 1ms; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 0) - So(res[2].Result, ShouldHaveLength, 0) - So(res[1].Status, ShouldEqual, "ERR_TO") - So(res[1].Detail, ShouldEqual, "Query timeout of 1ms exceeded") - - }) - - Convey("Creating a record with unbounded map or array keys succeeds", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |test:1000|; - CREATE person:test SET tests=(SELECT id FROM test); - SELECT * FROM person:test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 1000) - So(res[2].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[3].Result[0]).Get("tests").Data(), ShouldHaveLength, 1000) - - }) - -} diff --git a/db/db.gen.go b/db/db.gen.go deleted file mode 100644 index 5741f505..00000000 --- a/db/db.gen.go +++ /dev/null @@ -1,493 +0,0 @@ -//go:build go1.6 -// +build go1.6 - -// Code generated by codecgen - DO NOT EDIT. - -package db - -import ( - "errors" - codec1978 "github.com/ugorji/go/codec" - "runtime" - "strconv" -) - -const ( - // ----- content types ---- - codecSelferCcUTF87585 = 1 - codecSelferCcRAW7585 = 255 - // ----- value types used ---- - codecSelferValueTypeArray7585 = 10 - codecSelferValueTypeMap7585 = 9 - codecSelferValueTypeString7585 = 6 - codecSelferValueTypeInt7585 = 2 - codecSelferValueTypeUint7585 = 3 - codecSelferValueTypeFloat7585 = 4 - codecSelferValueTypeNil7585 = 1 - codecSelferBitsize7585 = uint8(32 << (^uint(0) >> 63)) - codecSelferDecContainerLenNil7585 = -2147483648 -) - -var ( - errCodecSelferOnlyMapOrArrayEncodeToStruct7585 = errors.New(`only encoded map or array can be decoded into a struct`) -) - -type codecSelfer7585 struct{} - -func codecSelfer7585False() bool { return false } -func codecSelfer7585True() bool { return true } - -func init() { - if codec1978.GenVersion != 25 { - _, file, _, _ := runtime.Caller(0) - ver := strconv.FormatInt(int64(codec1978.GenVersion), 10) - panic(errors.New("codecgen version mismatch: current: 25, need " + ver + ". Re-generate file: " + file)) - } -} - -func (Response) codecSelferViaCodecgen() {} -func (x *Response) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyq2 = [4]bool{ // should field at this index be written? - x.Time != "", // time - x.Status != "", // status - x.Detail != "", // detail - len(x.Result) != 0, // result - } - _ = yyq2 - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - if yyq2[0] { - r.EncodeString(string(x.Time)) - } else { - r.EncodeString("") - } - z.EncWriteArrayElem() - if yyq2[1] { - r.EncodeString(string(x.Status)) - } else { - r.EncodeString("") - } - z.EncWriteArrayElem() - if yyq2[2] { - r.EncodeString(string(x.Detail)) - } else { - r.EncodeString("") - } - z.EncWriteArrayElem() - if yyq2[3] { - if x.Result == nil { - r.EncodeNil() - } else { - z.F.EncSliceIntfV(x.Result, e) - } // end block: if x.Result slice == nil - } else { - r.EncodeNil() - } - z.EncWriteArrayEnd() - } else { - var yynn2 int - for _, b := range yyq2 { - if b { - yynn2++ - } - } - z.EncWriteMapStart(yynn2) - yynn2 = 0 - if yyq2[0] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"time\"") - } else { - r.EncodeString(`time`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Time)) - } - if yyq2[1] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"status\"") - } else { - r.EncodeString(`status`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Status)) - } - if yyq2[2] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"detail\"") - } else { - r.EncodeString(`detail`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Detail)) - } - if yyq2[3] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"result\"") - } else { - r.EncodeString(`result`) - } - z.EncWriteMapElemValue() - if x.Result == nil { - r.EncodeNil() - } else { - z.F.EncSliceIntfV(x.Result, e) - } // end block: if x.Result slice == nil - } - z.EncWriteMapEnd() - } - } -} - -func (x *Response) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil7585 { - *(x) = Response{} - } else if yyct2 == codecSelferValueTypeMap7585 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray7585 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct7585) - } -} - -func (x *Response) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "time": - x.Time = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "status": - x.Status = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "detail": - x.Detail = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "result": - z.F.DecSliceIntfX(&x.Result, d) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Response) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj9 int - var yyb9 bool - var yyhl9 bool = l >= 0 - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Time = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Status = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Detail = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - z.F.DecSliceIntfX(&x.Result, d) - for { - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj9-1, "") - } -} - -func (x *Response) IsCodecEmpty() bool { - return !(x.Time != "" || x.Status != "" || x.Detail != "" || len(x.Result) != 0 || false) -} - -func (Dispatch) codecSelferViaCodecgen() {} -func (x *Dispatch) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyq2 = [3]bool{ // should field at this index be written? - x.Query != "", // query - x.Action != "", // action - x.Result != nil, // result - } - _ = yyq2 - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyq2[0] { - r.EncodeString(string(x.Query)) - } else { - r.EncodeString("") - } - z.EncWriteArrayElem() - if yyq2[1] { - r.EncodeString(string(x.Action)) - } else { - r.EncodeString("") - } - z.EncWriteArrayElem() - if yyq2[2] { - z.EncFallback(x.Result) - } else { - r.EncodeNil() - } - z.EncWriteArrayEnd() - } else { - var yynn2 int - for _, b := range yyq2 { - if b { - yynn2++ - } - } - z.EncWriteMapStart(yynn2) - yynn2 = 0 - if yyq2[0] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"query\"") - } else { - r.EncodeString(`query`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Query)) - } - if yyq2[1] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"action\"") - } else { - r.EncodeString(`action`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Action)) - } - if yyq2[2] { - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"result\"") - } else { - r.EncodeString(`result`) - } - z.EncWriteMapElemValue() - z.EncFallback(x.Result) - } - z.EncWriteMapEnd() - } - } -} - -func (x *Dispatch) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil7585 { - *(x) = Dispatch{} - } else if yyct2 == codecSelferValueTypeMap7585 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray7585 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct7585) - } -} - -func (x *Dispatch) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "query": - x.Query = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "action": - x.Action = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "result": - z.DecFallback(&x.Result, true) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Dispatch) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer7585 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Query = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Action = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - z.DecFallback(&x.Result, true) - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *Dispatch) IsCodecEmpty() bool { - return !(x.Query != "" || x.Action != "" || x.Result != nil || false) -} diff --git a/db/db.go b/db/db.go deleted file mode 100644 index 69a3724c..00000000 --- a/db/db.go +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "io" - "os" - - "context" - - "net/http" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - - _ "github.com/surrealdb/surrealdb/kvs/rixxdb" -) - -var KV string - -var NIL string - -var ENV string - -// Response is a response from the database -type Response struct { - Time string `codec:"time,omitempty"` - Status string `codec:"status,omitempty"` - Detail string `codec:"detail,omitempty"` - Result []interface{} `codec:"result,omitempty"` -} - -// Dispatch is a dispatch from the database -type Dispatch struct { - Query string `codec:"query,omitempty"` - Action string `codec:"action,omitempty"` - Result interface{} `codec:"result,omitempty"` -} - -func init() { - ENV = os.Getenv(varKeyEnv) -} - -// Setup sets up the connection with the data layer -func Setup(opts *cnf.Options) (err error) { - KV = cnf.Settings.DB.Base - err = tidy() - return -} - -// Exit shuts down the connection with the data layer -func Exit(opts *cnf.Options) (err error) { - sockets.Range(func(key, val interface{}) bool { - id, so := key.(string), val.(*socket) - deregister(so.fibre, id)() - return true - }) - return - -} - -// Import loads database operations from a reader. -// This can be used to playback a database snapshot -// into an already running database. -func Sync(rw interface{}) (err error) { - switch v := rw.(type) { - case io.Reader: - return kvs.Import(v) - case io.Writer: - return kvs.Export(v) - default: - return nil - } -} - -// Export saves all database operations to a writer. -// This can be used to save a database snapshot -// to a secondary file or stream. -func Export(fib *fibre.Context, ns, db string) (err error) { - return export(fib, ns, db) -} - -// Socket registers a websocket for live queries -// returning two callback functions. The first -// function should be called when the websocket -// connects, and the second function should be -// called when the websocket disconnects. -func Socket(fib *fibre.Context, id string) (beg, end func()) { - return register(fib, id), deregister(fib, id) -} - -// Execute parses a single sql query, or multiple -// sql queries, and executes them serially against -// the underlying data layer. -func Execute(fib *fibre.Context, txt interface{}, vars map[string]interface{}) (out []*Response, err error) { - - // Parse the received SQL batch query strings - // into SQL ASTs, using any immutable preset - // variables if set. - - ast, err := sql.Parse(txt) - if err != nil { - return - } - - // Process the parsed SQL batch query using - // the predefined query variables. - - return Process(fib, ast, vars) - -} - -// Process takes a parsed set of sql queries and -// executes them serially against the underlying -// data layer. -func Process(fib *fibre.Context, ast *sql.Query, vars map[string]interface{}) (out []*Response, err error) { - - // If no preset variables have been defined - // then ensure that the variables is - // instantiated for future use. - - if vars == nil { - vars = make(map[string]interface{}) - } - - // Fetch any variables which have been set - // on the connection. These might have been - // set on the WebSocket or using HTTP Headers. - - if sess := fib.Get(ctxKeyVars); sess != nil { - for key, val := range sess.(map[string]interface{}) { - vars[key] = val - } - } - - // Get the unique id for this connection - // so that we can assign it to the context - // and detect any websocket notifications. - - id := fib.Uniq() - - // Assign the authentication data to the - // context so that we can log the auth kind - // and the auth variable data to the request. - - auth := fib.Get(ctxKeyAuth).(*cnf.Auth) - - // Ensure that the specified environment - // variable 'ENV' is available to the - // request, to detect the environment. - - vars[varKeyEnv] = ENV - - // Ensure that the current authentication - // data is made available as a runtime - // variable to the query layer. - - vars[varKeyAuth] = auth.Data - - // Ensure that the current authentication - // scope is made available as a runtime - // variable to the query layer. - - vars[varKeyScope] = auth.Scope - - // Ensure that the session details, such - // as id, ip, and origin, are available on - // the 'conn' object on each query. - - vars[varKeySession] = session(fib) - - // Create a new context so that we can quit - // all goroutine workers if the http client - // itself is closed before finishing. - - ctx, quit := context.WithCancel(fib.Context()) - - // When this function has finished ensure - // that we cancel this context so that any - // associated resources are released. - - defer quit() - - // Assign the Fibre http request data to the - // context so that we can trace all subsequent - // queries to alongside the http request. - - ctx = context.WithValue(ctx, ctxKeyFibre, fib) - - // Assign the authentication data to the - // context so that we can log the auth kind - // and the auth variable data to the request. - - ctx = context.WithValue(ctx, ctxKeyKind, auth.Kind) - - // Add the request variables to the context - // so that we can access them at a later - // stage within the nested callbacks. - - ctx = context.WithValue(ctx, ctxKeyVars, data.Consume(vars)) - - // If the current connection is a normal http - // connection then force quit any running - // queries if the http socket closes. - - if _, ok := fib.Response().Writer().(http.CloseNotifier); ok { - - exit := fib.Response().CloseNotify() - done := make(chan struct{}) - defer close(done) - - go func() { - select { - case <-done: - case <-exit: - quit() - } - }() - - } - - // Create a new query executor with the query - // details, and the current runtime variables - // and execute the queries within. - - executor := newExecutor(id, auth.NS, auth.DB) - - // Execute the parsed SQL syntax tree in a - // separate goroutine so that we can send - // the output in chunks to the client. - - go executor.execute(ctx, ast) - - // Send all flushed asynchronous messages - // to the websocket connections which are - // listening to the queries. - - defer send(id) - - // Wait for all of the processed queries to - // return results, buffer the output, and - // return the output when finished. - - for { - select { - case <-ctx.Done(): - return nil, fibre.NewHTTPError(504) - case res, open := <-executor.send: - if !open { - return - } - out = append(out, res) - } - } - - return - -} diff --git a/db/db_test.go b/db/db_test.go deleted file mode 100644 index 99628a1c..00000000 --- a/db/db_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "net/http/httptest" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/util/uuid" -) - -var req *fibre.Request -var res *fibre.Response - -func init() { - req = &fibre.Request{Request: httptest.NewRequest("GET", "/", nil)} - res = &fibre.Response{} -} - -func setupDB(workers int) { - - cnf.Settings = &cnf.Options{} - cnf.Settings.DB.Path = "memory" - cnf.Settings.DB.Base = "surreal" - workerCount = workers - - kvs.Setup(cnf.Settings) - - Setup(cnf.Settings) - -} - -func permsKV() (ctx *fibre.Context) { - - ctx = fibre.NewContext(req, res, nil) - ctx.Set("id", uuid.New().String()) - ctx.Set("auth", &cnf.Auth{ - Kind: cnf.AuthKV, - NS: "test", - DB: "test", - }) - - return ctx - -} - -func permsSC() (ctx *fibre.Context) { - - ctx = fibre.NewContext(req, res, nil) - ctx.Set("id", uuid.New().String()) - ctx.Set("auth", &cnf.Auth{ - Kind: cnf.AuthSC, - NS: "test", - DB: "test", - }) - - return ctx - -} diff --git a/db/define.go b/db/define.go deleted file mode 100644 index abe52150..00000000 --- a/db/define.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance wdbh the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "golang.org/x/crypto/bcrypt" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" - "github.com/surrealdb/surrealdb/util/rand" -) - -func (e *executor) executeDefineNamespace(ctx context.Context, ast *sql.DefineNamespaceStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthKV); err != nil { - return nil, err - } - - // Save the namespace definition - nkey := &keys.NS{KV: KV, NS: ast.Name.VA} - _, err = e.tx.Put(ctx, 0, nkey.Encode(), ast.Encode()) - - return - -} - -func (e *executor) executeDefineDatabase(ctx context.Context, ast *sql.DefineDatabaseStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - e.tx.AddNS(ctx, e.ns) - - // Save the database definition - dkey := &keys.DB{KV: KV, NS: e.ns, DB: ast.Name.VA} - _, err = e.tx.Put(ctx, 0, dkey.Encode(), ast.Encode()) - - return - -} - -func (e *executor) executeDefineLogin(ctx context.Context, ast *sql.DefineLoginStatement) (out []interface{}, err error) { - - ast.Code = rand.New(128) - - switch len(ast.Hash) { - default: - ast.Pass = ast.Hash - case 0: - ast.Pass, _ = bcrypt.GenerateFromPassword(ast.Pass, bcrypt.DefaultCost) - } - - switch ast.Kind { - case sql.NAMESPACE: - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - e.tx.AddNS(ctx, e.ns) - - // Save the login definition - ukey := &keys.NU{KV: KV, NS: e.ns, US: ast.User.VA} - _, err = e.tx.Put(ctx, 0, ukey.Encode(), ast.Encode()) - - case sql.DATABASE: - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - e.tx.AddDB(ctx, e.ns, e.db) - - // Save the login definition - ukey := &keys.DU{KV: KV, NS: e.ns, DB: e.db, US: ast.User.VA} - _, err = e.tx.Put(ctx, 0, ukey.Encode(), ast.Encode()) - - } - - return - -} - -func (e *executor) executeDefineToken(ctx context.Context, ast *sql.DefineTokenStatement) (out []interface{}, err error) { - - switch ast.Kind { - case sql.NAMESPACE: - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - e.tx.AddNS(ctx, e.ns) - - // Save the token definition - tkey := &keys.NT{KV: KV, NS: e.ns, TK: ast.Name.VA} - _, err = e.tx.Put(ctx, 0, tkey.Encode(), ast.Encode()) - - case sql.DATABASE: - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - e.tx.AddDB(ctx, e.ns, e.db) - - // Save the token definition - tkey := &keys.DT{KV: KV, NS: e.ns, DB: e.db, TK: ast.Name.VA} - _, err = e.tx.Put(ctx, 0, tkey.Encode(), ast.Encode()) - - case sql.SCOPE: - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - e.tx.AddDB(ctx, e.ns, e.db) - - // Save the token definition - tkey := &keys.ST{KV: KV, NS: e.ns, DB: e.db, SC: ast.What.VA, TK: ast.Name.VA} - _, err = e.tx.Put(ctx, 0, tkey.Encode(), ast.Encode()) - - } - - return - -} - -func (e *executor) executeDefineScope(ctx context.Context, ast *sql.DefineScopeStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - ast.Code = rand.New(128) - - e.tx.AddDB(ctx, e.ns, e.db) - - // Remove the scope definition - skey := &keys.SC{KV: KV, NS: e.ns, DB: e.db, SC: ast.Name.VA} - _, err = e.tx.Put(ctx, 0, skey.Encode(), ast.Encode()) - - return - -} - -func (e *executor) executeDefineEvent(ctx context.Context, ast *sql.DefineEventStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.AddTB(ctx, e.ns, e.db, TB.TB) - - // Remove the event definition - ekey := &keys.EV{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, EV: ast.Name.VA} - if _, err = e.tx.Put(ctx, 0, ekey.Encode(), ast.Encode()); err != nil { - return nil, err - } - - } - - return - -} - -func (e *executor) executeDefineField(ctx context.Context, ast *sql.DefineFieldStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.AddTB(ctx, e.ns, e.db, TB.TB) - - // Save the field definition - fkey := &keys.FD{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, FD: ast.Name.VA} - if _, err = e.tx.Put(ctx, 0, fkey.Encode(), ast.Encode()); err != nil { - return nil, err - } - - } - - return - -} - -func (e *executor) executeDefineIndex(ctx context.Context, ast *sql.DefineIndexStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.AddTB(ctx, e.ns, e.db, TB.TB) - - // Save the index definition - ikey := &keys.IX{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, IX: ast.Name.VA} - if _, err = e.tx.Put(ctx, 0, ikey.Encode(), ast.Encode()); err != nil { - return nil, err - } - - // Remove the index resource data - dkey := &keys.Index{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, IX: ast.Name.VA, FD: keys.Ignore} - if _, err = e.tx.ClrP(ctx, dkey.Encode(), 0); err != nil { - return nil, err - } - - // Process the index resource data - uctx := context.WithValue(ctx, ctxKeyForce, true) - ustm := &sql.UpdateStatement{What: []sql.Expr{TB}} - if _, err = e.executeUpdate(uctx, ustm); err != nil { - return nil, err - } - - } - - return - -} - -func (e *executor) executeDefineTable(ctx context.Context, ast *sql.DefineTableStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - e.tx.AddDB(ctx, e.ns, e.db) - - for _, TB := range ast.What { - - ast.Name = sql.NewIdent(TB.TB) - - // Save the table definition - tkey := &keys.TB{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB} - if _, err = e.tx.Put(ctx, 0, tkey.Encode(), ast.Encode()); err != nil { - return nil, err - } - - if ast.Lock { - - // Remove the table resource data - dkey := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB} - if _, err = e.tx.ClrP(ctx, dkey.Encode(), 0); err != nil { - return nil, err - } - - for _, FT := range ast.From { - - // Save the foreign table definition - tkey := &keys.FT{KV: KV, NS: e.ns, DB: e.db, TB: FT.TB, FT: TB.TB} - if _, err = e.tx.Put(ctx, 0, tkey.Encode(), ast.Encode()); err != nil { - return nil, err - } - - // Process the table resource data - uctx := context.WithValue(ctx, ctxKeyForce, true) - ustm := &sql.UpdateStatement{What: []sql.Expr{FT}} - if _, err = e.executeUpdate(uctx, ustm); err != nil { - return nil, err - } - - } - - } - - } - - return - -} diff --git a/db/define_test.go b/db/define_test.go deleted file mode 100644 index 479cc836..00000000 --- a/db/define_test.go +++ /dev/null @@ -1,1383 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestDefine(t *testing.T) { - - Convey("Define a namespace", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE NAMESPACE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - - }) - - Convey("Define a database", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE DATABASE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - - }) - - Convey("Define a scope", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE SCOPE test SESSION 1h0m0s - SIGNUP AS ( - IF $ip IN ["127.0.0.1", "213.172.165.134"] THEN - (CREATE user SET email=$user, pass=bcrypt.generate($pass)) - END - ) - SIGNIN AS ( - SELECT * FROM user WHERE email=$user AND bcrypt.compare(pass, $pass) - ) - ON SIGNUP ( - UPDATE $id SET times.created=time.now(); - CREATE activity SET kind="signup", user=$id; - ) - ON SIGNIN ( - UPDATE $id SET times.login=time.now(); - CREATE activity SET kind="signin", user=$id; - ) - ; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - - }) - - Convey("Define a schemaless table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person SCHEMALESS; - DEFINE FIELD test ON person TYPE boolean; - UPDATE person:test SET test=true, other="text"; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, true) - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, "text") - - }) - - Convey("Define a schemafull table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person SCHEMAFULL; - DEFINE FIELD test ON person TYPE boolean; - UPDATE person:test SET test=true, other="text"; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(data.Consume(res[3].Result[0]).Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "tb": "person", - "id": "test", - }, - "test": true, - }) - - }) - - Convey("Define a schemafull table with nil values", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person SCHEMAFULL; - DEFINE FIELD test ON person TYPE boolean; - UPDATE person:test SET test=true, other=NULL; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(data.Consume(res[3].Result[0]).Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "tb": "person", - "id": "test", - }, - "test": true, - }) - - }) - - Convey("Define a schemafull table with nested records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person SCHEMAFULL; - DEFINE FIELD test ON person TYPE record (person); - UPDATE person:test SET test=person:other; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(data.Consume(res[3].Result[0]).Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "tb": "person", - "id": "test", - }, - "test": &sql.Thing{"person", "other"}, - }) - - }) - - Convey("Define a schemafull table with nested set records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person SCHEMAFULL; - DEFINE FIELD test ON person TYPE array; - DEFINE FIELD test.* ON person TYPE record (person); - UPDATE person:test SET test=[], test+=person:one, test+=person:two; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(data.Consume(res[4].Result[0]).Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "tb": "person", - "id": "test", - }, - "test": []interface{}{ - &sql.Thing{"person", "one"}, - &sql.Thing{"person", "two"}, - }, - }) - - }) - - Convey("Convert a schemaless to schemafull table, and ensure schemaless fields are still output", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person SCHEMALESS; - UPDATE person:test SET test=true, other="text"; - DEFINE TABLE person SCHEMAFULL; - DEFINE FIELD test ON person TYPE boolean; - SELECT * FROM person; - DEFINE FIELD other ON person TYPE string; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, true) - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, "text") - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[0]).Get("other").Data(), ShouldEqual, "text") - So(data.Consume(res[7].Result[0]).Get("test").Data(), ShouldEqual, true) - So(data.Consume(res[7].Result[0]).Get("other").Data(), ShouldEqual, "text") - - }) - - Convey("Define a drop table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person DROP; - UPDATE person:test; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 0) - - }) - - Convey("Define a foreign table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE temp AS SELECT name FROM person; - UPDATE person:test SET name="Test", test=true; - SELECT * FROM person; - SELECT * FROM temp; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "temp") - So(data.Consume(res[4].Result[0]).Get("name").Data(), ShouldEqual, "Test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, nil) - - }) - - Convey("Define a foreign table with a where clause", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE temp AS SELECT name FROM person WHERE test=true; - UPDATE person:one SET name="Test", test=true; - UPDATE person:two SET name="Test", test=false; - SELECT * FROM person; - SELECT * FROM temp; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 2) - So(res[5].Result, ShouldHaveLength, 1) - So(data.Consume(res[5].Result[0]).Get("meta.id").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("meta.tb").Data(), ShouldEqual, "temp") - So(data.Consume(res[5].Result[0]).Get("name").Data(), ShouldEqual, "Test") - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, nil) - - }) - - Convey("Define a foreign table with a group by clause", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person_age AS SELECT count(*) AS count, age FROM person WHERE test=true GROUP BY age; - UPDATE person:1 SET name="Test", test=true, age=30; - UPDATE person:2 SET name="Test", test=true, age=32; - UPDATE person:3 SET name="Test", test=true, age=30; - SELECT * FROM person ORDER BY meta.id; - SELECT * FROM person_age ORDER BY meta.id; - UPDATE person:3 SET name="Test", test=true, age=32; - SELECT * FROM person_age ORDER BY meta.id; - UPDATE person:3 SET name="Test", test=false, age=32; - SELECT * FROM person_age ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 3) - So(res[6].Result, ShouldHaveLength, 2) - So(data.Consume(res[6].Result[0]).Get("meta.id").Data(), ShouldEqual, "[30]") - So(data.Consume(res[6].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[6].Result[0]).Get("count").Data(), ShouldEqual, 2) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldBeNil) - So(data.Consume(res[6].Result[0]).Get("test").Data(), ShouldBeNil) - So(data.Consume(res[6].Result[1]).Get("meta.id").Data(), ShouldEqual, "[32]") - So(data.Consume(res[6].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[6].Result[1]).Get("count").Data(), ShouldEqual, 1) - So(data.Consume(res[6].Result[1]).Get("name").Data(), ShouldBeNil) - So(data.Consume(res[6].Result[1]).Get("test").Data(), ShouldBeNil) - So(res[7].Result, ShouldHaveLength, 1) - So(res[8].Result, ShouldHaveLength, 2) - So(data.Consume(res[8].Result[0]).Get("meta.id").Data(), ShouldEqual, "[30]") - So(data.Consume(res[8].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[8].Result[0]).Get("count").Data(), ShouldEqual, 1) - So(data.Consume(res[8].Result[0]).Get("name").Data(), ShouldBeNil) - So(data.Consume(res[8].Result[0]).Get("test").Data(), ShouldBeNil) - So(data.Consume(res[8].Result[1]).Get("meta.id").Data(), ShouldEqual, "[32]") - So(data.Consume(res[8].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[8].Result[1]).Get("count").Data(), ShouldEqual, 2) - So(data.Consume(res[8].Result[1]).Get("name").Data(), ShouldBeNil) - So(data.Consume(res[8].Result[1]).Get("test").Data(), ShouldBeNil) - So(res[9].Result, ShouldHaveLength, 1) - So(res[10].Result, ShouldHaveLength, 2) - So(data.Consume(res[10].Result[0]).Get("meta.id").Data(), ShouldEqual, "[30]") - So(data.Consume(res[10].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[10].Result[0]).Get("count").Data(), ShouldEqual, 1) - So(data.Consume(res[10].Result[0]).Get("name").Data(), ShouldBeNil) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldBeNil) - So(data.Consume(res[10].Result[1]).Get("meta.id").Data(), ShouldEqual, "[32]") - So(data.Consume(res[10].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[10].Result[1]).Get("count").Data(), ShouldEqual, 1) - So(data.Consume(res[10].Result[1]).Get("name").Data(), ShouldBeNil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldBeNil) - - }) - - Convey("Define multiple foreign tables with group by clauses", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE TABLE person_f AS SELECT * FROM person WHERE gender='f'; - DEFINE TABLE person_m AS SELECT * FROM person WHERE gender='m'; - DEFINE TABLE person_age AS - SELECT count(*) AS count, - distinct(id), - distinct(age), - math.min(age), - math.max(age), - math.sum(age), - math.mean(age), - math.stddev(age), - math.variance(age), - age - FROM person GROUP BY age - ; - DEFINE TABLE person_gender AS - SELECT count(*) AS count, - distinct(id), - distinct(age), - math.min(age), - math.max(age), - math.sum(age), - math.mean(age), - math.stddev(age), - math.variance(age), - gender - FROM person GROUP BY gender - ; - DEFINE TABLE person_age_gender AS - SELECT count(*) AS count, - distinct(id), - distinct(age), - math.min(age), - math.max(age), - math.sum(age), - math.mean(age), - math.stddev(age), - math.variance(age), - age, gender - FROM person GROUP BY age, gender - ; - UPDATE |person:10| SET name="Test", test=true, age=30, gender='f'; - UPDATE |person:10| SET name="Test", test=true, age=32, gender='m'; - UPDATE |person:10| SET name="Test", test=true, age=30, gender='m'; - UPDATE |person:10| SET name="Test", test=true, age=31, gender='f'; - UPDATE |person:10| SET name="Test", test=true, age=29, gender='m'; - SELECT * FROM person ORDER BY meta.id; - SELECT * FROM person_f ORDER BY meta.id; - SELECT * FROM person_m ORDER BY meta.id; - SELECT * FROM person_age ORDER BY meta.id; - SELECT * FROM person_gender ORDER BY meta.id; - SELECT * FROM person_age_gender ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 17) - So(res[6].Result, ShouldHaveLength, 10) - So(res[7].Result, ShouldHaveLength, 10) - So(res[8].Result, ShouldHaveLength, 10) - So(res[9].Result, ShouldHaveLength, 10) - So(res[10].Result, ShouldHaveLength, 10) - So(res[11].Result, ShouldHaveLength, 50) - So(res[12].Result, ShouldHaveLength, 20) - So(res[13].Result, ShouldHaveLength, 30) - So(res[14].Result, ShouldHaveLength, 4) - So(data.Consume(res[14].Result[0]).Get("meta.id").Data(), ShouldEqual, "[29]") - So(data.Consume(res[14].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[14].Result[0]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[14].Result[0]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[0]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[14].Result[0]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[0]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[14].Result[0]).Get("math.min(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[14].Result[0]).Get("math.max(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[14].Result[0]).Get("math.sum(age)").Data(), ShouldEqual, 290) - So(data.Consume(res[14].Result[0]).Get("math.mean(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[14].Result[0]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[0]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[1]).Get("meta.id").Data(), ShouldEqual, "[30]") - So(data.Consume(res[14].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[14].Result[1]).Get("count").Data(), ShouldEqual, 20) - So(data.Consume(res[14].Result[1]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[1]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 20) - So(data.Consume(res[14].Result[1]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[1]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[14].Result[1]).Get("math.min(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[14].Result[1]).Get("math.max(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[14].Result[1]).Get("math.sum(age)").Data(), ShouldEqual, 600) - So(data.Consume(res[14].Result[1]).Get("math.mean(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[14].Result[1]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[1]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[2]).Get("meta.id").Data(), ShouldEqual, "[31]") - So(data.Consume(res[14].Result[2]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[14].Result[2]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[14].Result[2]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[2]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[14].Result[2]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[2]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[14].Result[2]).Get("math.min(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[14].Result[2]).Get("math.max(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[14].Result[2]).Get("math.sum(age)").Data(), ShouldEqual, 310) - So(data.Consume(res[14].Result[2]).Get("math.mean(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[14].Result[2]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[2]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[3]).Get("meta.id").Data(), ShouldEqual, "[32]") - So(data.Consume(res[14].Result[3]).Get("meta.tb").Data(), ShouldEqual, "person_age") - So(data.Consume(res[14].Result[3]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[14].Result[3]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[3]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[14].Result[3]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[14].Result[3]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[14].Result[3]).Get("math.min(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[14].Result[3]).Get("math.max(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[14].Result[3]).Get("math.sum(age)").Data(), ShouldEqual, 320) - So(data.Consume(res[14].Result[3]).Get("math.mean(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[14].Result[3]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[14].Result[3]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(res[15].Result, ShouldHaveLength, 2) - So(data.Consume(res[15].Result[0]).Get("meta.id").Data(), ShouldEqual, "[f]") - So(data.Consume(res[15].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person_gender") - So(data.Consume(res[15].Result[0]).Get("count").Data(), ShouldEqual, 20) - So(data.Consume(res[15].Result[0]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[15].Result[0]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 20) - So(data.Consume(res[15].Result[0]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[15].Result[0]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 2) - So(data.Consume(res[15].Result[0]).Get("math.min(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[15].Result[0]).Get("math.max(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[15].Result[0]).Get("math.sum(age)").Data(), ShouldEqual, 610) - So(data.Consume(res[15].Result[0]).Get("math.mean(age)").Data(), ShouldEqual, 30.5) - So(data.Consume(res[15].Result[0]).Get("math.stddev(age)").Data(), ShouldEqual, 0.512989176042577) - So(data.Consume(res[15].Result[0]).Get("math.variance(age)").Data(), ShouldEqual, 0.26315789473684215) - So(data.Consume(res[15].Result[1]).Get("meta.id").Data(), ShouldEqual, "[m]") - So(data.Consume(res[15].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person_gender") - So(data.Consume(res[15].Result[1]).Get("count").Data(), ShouldEqual, 30) - So(data.Consume(res[15].Result[1]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[15].Result[1]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 30) - So(data.Consume(res[15].Result[1]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[15].Result[1]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 3) - So(data.Consume(res[15].Result[1]).Get("math.min(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[15].Result[1]).Get("math.max(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[15].Result[1]).Get("math.sum(age)").Data(), ShouldEqual, 910) - So(data.Consume(res[15].Result[1]).Get("math.mean(age)").Data(), ShouldEqual, 30.333333333333332) - So(data.Consume(res[15].Result[1]).Get("math.stddev(age)").Data(), ShouldEqual, 1.2685406585123122) - So(data.Consume(res[15].Result[1]).Get("math.variance(age)").Data(), ShouldEqual, 1.6091954022988506) - So(res[16].Result, ShouldHaveLength, 5) - So(data.Consume(res[16].Result[0]).Get("meta.id").Data(), ShouldEqual, "[29 m]") - So(data.Consume(res[16].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person_age_gender") - So(data.Consume(res[16].Result[0]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[16].Result[0]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[0]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[16].Result[0]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[0]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[16].Result[0]).Get("math.min(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[16].Result[0]).Get("math.max(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[16].Result[0]).Get("math.sum(age)").Data(), ShouldEqual, 290) - So(data.Consume(res[16].Result[0]).Get("math.mean(age)").Data(), ShouldEqual, 29) - So(data.Consume(res[16].Result[0]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[0]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[1]).Get("meta.id").Data(), ShouldEqual, "[30 f]") - So(data.Consume(res[16].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person_age_gender") - So(data.Consume(res[16].Result[1]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[16].Result[1]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[1]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[16].Result[1]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[1]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[16].Result[1]).Get("math.min(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[16].Result[1]).Get("math.max(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[16].Result[1]).Get("math.sum(age)").Data(), ShouldEqual, 300) - So(data.Consume(res[16].Result[1]).Get("math.mean(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[16].Result[1]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[1]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[2]).Get("meta.id").Data(), ShouldEqual, "[30 m]") - So(data.Consume(res[16].Result[2]).Get("meta.tb").Data(), ShouldEqual, "person_age_gender") - So(data.Consume(res[16].Result[2]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[16].Result[2]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[2]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[16].Result[2]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[2]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[16].Result[2]).Get("math.min(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[16].Result[2]).Get("math.max(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[16].Result[2]).Get("math.sum(age)").Data(), ShouldEqual, 300) - So(data.Consume(res[16].Result[2]).Get("math.mean(age)").Data(), ShouldEqual, 30) - So(data.Consume(res[16].Result[2]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[2]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[3]).Get("meta.id").Data(), ShouldEqual, "[31 f]") - So(data.Consume(res[16].Result[3]).Get("meta.tb").Data(), ShouldEqual, "person_age_gender") - So(data.Consume(res[16].Result[3]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[16].Result[3]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[3]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[16].Result[3]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[3]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[16].Result[3]).Get("math.min(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[16].Result[3]).Get("math.max(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[16].Result[3]).Get("math.sum(age)").Data(), ShouldEqual, 310) - So(data.Consume(res[16].Result[3]).Get("math.mean(age)").Data(), ShouldEqual, 31) - So(data.Consume(res[16].Result[3]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[3]).Get("math.variance(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[4]).Get("meta.id").Data(), ShouldEqual, "[32 m]") - So(data.Consume(res[16].Result[4]).Get("meta.tb").Data(), ShouldEqual, "person_age_gender") - So(data.Consume(res[16].Result[4]).Get("count").Data(), ShouldEqual, 10) - So(data.Consume(res[16].Result[4]).Get("distinct(id)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[4]).Get("distinct(id)").Data().([]interface{}), ShouldHaveLength, 10) - So(data.Consume(res[16].Result[4]).Get("distinct(age)").Data(), ShouldHaveSameTypeAs, []interface{}{}) - So(data.Consume(res[16].Result[4]).Get("distinct(age)").Data().([]interface{}), ShouldHaveLength, 1) - So(data.Consume(res[16].Result[4]).Get("math.min(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[16].Result[4]).Get("math.max(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[16].Result[4]).Get("math.sum(age)").Data(), ShouldEqual, 320) - So(data.Consume(res[16].Result[4]).Get("math.mean(age)").Data(), ShouldEqual, 32) - So(data.Consume(res[16].Result[4]).Get("math.stddev(age)").Data(), ShouldEqual, 0) - So(data.Consume(res[16].Result[4]).Get("math.variance(age)").Data(), ShouldEqual, 0) - - }) - - Convey("Define a table with permission specified so only specified records are visible", t, func() { - - setupDB(workerCount) - - func() { - - txt := ` - USE NS test DB test; - DEFINE TABLE person PERMISSIONS FOR SELECT WHERE string.startsWith(name, "J") FOR CREATE, UPDATE FULL; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - - }() - - func() { - - txt := ` - USE NS test DB test; - UPDATE person:1 SET name="Tobie"; - UPDATE person:2 SET name="Jaime"; - SELECT * FROM person; - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 2) - - }() - - }) - - Convey("Assert the value of a field", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE FIELD test ON person TYPE number ASSERT $after >= 0 AND $after <= 10; - UPDATE person:1; - UPDATE person:2 SET test = 5; - UPDATE person:3 SET test = 50; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[2].Status, ShouldEqual, "ERR_FD") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "ERR_FD") - So(res[5].Result, ShouldHaveLength, 1) - - }) - - Convey("Assert the value of a field if it has been set", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE FIELD test ON person TYPE number ASSERT IF $after != null THEN $after >= 0 AND $after <= 10 ELSE true END; - UPDATE person:1; - UPDATE person:2 SET test = 5; - UPDATE person:3 SET test = 50; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "ERR_FD") - So(res[5].Result, ShouldHaveLength, 2) - - }) - - Convey("Specify the priority of a field so that it is processed after any dependent fields", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE FIELD name.first ON person; - DEFINE FIELD name.last ON person; - DEFINE FIELD name.full ON person VALUE string.join(' ', name.first, name.last) PRIORITY 10; - DEFINE FIELD name.alias ON person VALUE string.join(' ', name.full, "(aka. Toboman)") PRIORITY 20; - UPDATE person:test SET name.first="Tobias", name.last="Ottoman"; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(data.Consume(res[5].Result[0]).Get("name.first").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[5].Result[0]).Get("name.last").Data(), ShouldEqual, "Ottoman") - So(data.Consume(res[5].Result[0]).Get("name.full").Data(), ShouldEqual, "Tobias Ottoman") - So(data.Consume(res[5].Result[0]).Get("name.alias").Data(), ShouldEqual, "Tobias Ottoman (aka. Toboman)") - - }) - - Convey("Specify the permissions of a field so that it is only visible to the correct authentication levels", t, func() { - - setupDB(workerCount) - - func() { - - txt := ` - USE NS test DB test; - DEFINE TABLE person PERMISSIONS FULL; - DEFINE FIELD name ON person PERMISSIONS FULL; - DEFINE FIELD pass ON person PERMISSIONS NONE; - DEFINE FIELD test ON person PERMISSIONS FOR CREATE, UPDATE FULL FOR SELECT NONE; - DEFINE FIELD temp ON person PERMISSIONS NONE; - DEFINE FIELD temp.test ON person PERMISSIONS FULL; - UPDATE person:test SET name="Tobias", pass="qhmyjahdc4", test="k5n87urq8l", temp.test="zw3wf5ls39"; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - So(res[7].Result, ShouldHaveLength, 1) - So(data.Consume(res[7].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[7].Result[0]).Get("pass").Data(), ShouldEqual, "qhmyjahdc4") - So(data.Consume(res[7].Result[0]).Get("test").Data(), ShouldEqual, "k5n87urq8l") - So(data.Consume(res[7].Result[0]).Get("temp.test").Data(), ShouldEqual, "zw3wf5ls39") - So(res[8].Result, ShouldHaveLength, 1) - So(data.Consume(res[8].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[8].Result[0]).Get("pass").Data(), ShouldEqual, "qhmyjahdc4") - So(data.Consume(res[8].Result[0]).Get("test").Data(), ShouldEqual, "k5n87urq8l") - So(data.Consume(res[8].Result[0]).Get("temp.test").Data(), ShouldEqual, "zw3wf5ls39") - - }() - - func() { - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Silvana", pass="1f65flhfvq", test="35aptguqoj", temp.test="h08ryx3519"; - UPDATE person:2 SET name="Jonathan", pass="8k796m5mmj", test="1lzdhd6wzg", temp.test="xurnxp8a1e"; - SELECT * FROM person ORDER BY name; - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[1].Result[0]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[1].Result[0]).Get("temp.test").Data(), ShouldEqual, nil) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[2].Result[0]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[2].Result[0]).Get("temp.test").Data(), ShouldEqual, nil) - So(res[3].Result, ShouldHaveLength, 3) - So(data.Consume(res[3].Result[0]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[3].Result[0]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[3].Result[1]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[2]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[3].Result[2]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[2]).Get("temp.test").Data(), ShouldEqual, nil) - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM person ORDER BY name; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[1].Result[0]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, "1lzdhd6wzg") - So(data.Consume(res[1].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[1].Result[1]).Get("pass").Data(), ShouldEqual, nil) - So(data.Consume(res[1].Result[1]).Get("test").Data(), ShouldEqual, "35aptguqoj") - So(data.Consume(res[1].Result[2]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[1].Result[2]).Get("pass").Data(), ShouldEqual, "qhmyjahdc4") - So(data.Consume(res[1].Result[2]).Get("test").Data(), ShouldEqual, "k5n87urq8l") - - }() - - }) - - Convey("Define an event when a value changes", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN test > 1000 THEN (CREATE temp; CREATE test); - UPDATE person:test SET test = 1000; - UPDATE person:test SET test = 4000; - UPDATE person:test SET test = 2000; - UPDATE person:test SET test = 6000; - SELECT * FROM temp; - SELECT * FROM test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 3) - So(res[7].Result, ShouldHaveLength, 3) - - }) - - Convey("Define an event when a value increases", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $before.test < $after.test THEN (CREATE temp; CREATE test); - UPDATE person:test SET test = 1000; - UPDATE person:test SET test = 4000; - UPDATE person:test SET test = 2000; - UPDATE person:test SET test = 6000; - SELECT * FROM temp; - SELECT * FROM test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 2) - So(res[7].Result, ShouldHaveLength, 2) - - }) - - Convey("Define an event when a value increases beyond a threshold", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $before.test < 5000 AND $after.test > 5000 THEN (CREATE temp; CREATE test); - UPDATE person:test SET test = 1000; - UPDATE person:test SET test = 4000; - UPDATE person:test SET test = 2000; - UPDATE person:test SET test = 6000; - SELECT * FROM temp; - SELECT * FROM test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 1) - So(res[7].Result, ShouldHaveLength, 1) - - }) - - Convey("Define an event for both CREATE and UPDATE events separately", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT created ON person WHEN $method = "CREATE" THEN (CREATE created); - DEFINE EVENT updated ON person WHEN $method = "UPDATE" THEN (CREATE updated); - CREATE person:test SET test = 1000; - UPDATE person:test SET test = 4000; - UPDATE person:test SET test = 2000; - UPDATE person:test SET test = 2000; - UPDATE person:test SET test = 6000; - SELECT * FROM created; - SELECT * FROM updated; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 1) - So(res[7].Result, ShouldHaveLength, 1) - So(res[8].Result, ShouldHaveLength, 1) - So(res[9].Result, ShouldHaveLength, 3) - - }) - - Convey("Define an event when a value changes and set a foreign key on another table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $before.fk != $after.fk THEN (UPDATE $after.fk SET fk = $this); - UPDATE person:test SET fk = other:test; - SELECT * FROM other; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("fk").Data(), ShouldResemble, &sql.Thing{"person", "test"}) - - }) - - Convey("Define an event when a value changes and update a foreign key array on another table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $before.fk != $after.fk THEN (UPDATE $after.fk SET fks += $this); - UPDATE person:one SET fk = other:test; - UPDATE person:two SET fk = other:test; - SELECT * FROM other; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("fks").Data(), ShouldResemble, []interface{}{ - &sql.Thing{"person", "one"}, - &sql.Thing{"person", "two"}, - }) - - }) - - Convey("Define an event when a value changes and update and delete from a foreign key array on another table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $before.fk != $after.fk THEN ( - IF $method != "DELETE" THEN - (UPDATE $after.fk SET fks += $this) - ELSE - (UPDATE $before.fk SET fks -= $this) - END - ); - UPDATE person:one SET fk = other:test; - UPDATE person:two SET fk = other:test; - UPDATE person:tre SET fk = other:test; - DELETE FROM person; - SELECT * FROM other; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 0) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("fks").Data(), ShouldHaveLength, 0) - - }) - - Convey("Define an event on a table, and ensure it is not output with records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN true THEN (CREATE test); - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[2].Result, ShouldHaveLength, 0) - - }) - - Convey("Define an field on a table, and ensure it is not output with records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE FIELD test ON person; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[2].Result, ShouldHaveLength, 0) - - }) - - Convey("Define an index on a table, and ensure it is not output with records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS test; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[2].Result, ShouldHaveLength, 0) - - }) - - Convey("Define an index on a table, and ensure it allows duplicate record values", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS account, email; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="info@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 1) - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 3) - So(data.Consume(res[7].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - So(data.Consume(res[7].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "tre"}) - So(data.Consume(res[7].Result[2]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "two"}) - - }) - - Convey("Define a single-field unique index on a table, and ensure it prevents duplicate record values", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS email UNIQUE; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="info@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 0) - So(res[5].Status, ShouldEqual, "ERR_IX") - So(res[6].Result, ShouldHaveLength, 0) - So(res[6].Status, ShouldEqual, "ERR_IX") - So(res[7].Result, ShouldHaveLength, 1) - So(data.Consume(res[7].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - - }) - - Convey("Define a single-field unique index on a table, and ensure it prevents duplicate record values, after updating records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS email UNIQUE; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="test@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="test@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 0) - So(res[6].Status, ShouldEqual, "ERR_IX") - So(res[7].Result, ShouldHaveLength, 0) - So(res[7].Status, ShouldEqual, "ERR_IX") - So(res[8].Result, ShouldHaveLength, 2) - So(data.Consume(res[8].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - So(data.Consume(res[8].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "two"}) - - }) - - Convey("Define a single-field unique index on a table, and ensure it prevents duplicate record values, after deleting records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS email UNIQUE; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="test@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - DELETE person:one; - UPDATE person:tre SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="test@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 10) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 0) - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 0) - So(res[7].Status, ShouldEqual, "ERR_IX") - So(res[8].Result, ShouldHaveLength, 1) - So(res[8].Status, ShouldEqual, "OK") - So(res[9].Result, ShouldHaveLength, 2) - So(data.Consume(res[9].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "tre"}) - So(data.Consume(res[9].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "two"}) - - }) - - Convey("Define a multiple-field unique index on a table, and ensure it prevents duplicate record values", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS account, email UNIQUE; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:two SET account="two", email="info@demo.com"; - UPDATE person:tre SET account="tre", email="info@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 1) - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 3) - So(data.Consume(res[7].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - So(data.Consume(res[7].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "tre"}) - So(data.Consume(res[7].Result[2]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "two"}) - - }) - - Convey("Define a multiple-field unique index on a table, and ensure it prevents duplicate record values, after updating records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS account, email UNIQUE; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="test@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="test@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 0) - So(res[6].Status, ShouldEqual, "ERR_IX") - So(res[7].Result, ShouldHaveLength, 0) - So(res[7].Status, ShouldEqual, "ERR_IX") - So(res[8].Result, ShouldHaveLength, 2) - So(data.Consume(res[8].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - So(data.Consume(res[8].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "two"}) - - }) - - Convey("Define a multiple-field unique index on a table, and ensure it prevents duplicate record values, after deleting records", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS account, email UNIQUE; - UPDATE person:one SET account="one", email="info@demo.com"; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:one SET account="demo", email="test@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - DELETE person:one; - UPDATE person:tre SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="test@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 10) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 0) - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 0) - So(res[7].Status, ShouldEqual, "ERR_IX") - So(res[8].Result, ShouldHaveLength, 1) - So(res[8].Status, ShouldEqual, "OK") - So(res[9].Result, ShouldHaveLength, 2) - So(data.Consume(res[9].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "tre"}) - So(data.Consume(res[9].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "two"}) - - }) - - Convey("Define a multiple-field foreign record unique index on a table, and ensure it prevents duplicate record values", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS account, email UNIQUE; - UPDATE person:one SET account=tester:one, email="info@demo.com"; - UPDATE person:one SET account=tester:one, email="info@demo.com"; - UPDATE person:one SET account=tester:one, email="info@demo.com"; - UPDATE person:two SET account=tester:one, email="info@demo.com"; - UPDATE person:tre SET account=tester:two, email="info@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 0) - So(res[5].Status, ShouldEqual, "ERR_IX") - So(res[6].Result, ShouldHaveLength, 1) - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 2) - So(data.Consume(res[7].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - So(data.Consume(res[7].Result[1]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "tre"}) - - }) - - Convey("Redefine a unique index on a table, and ensure it prevents duplicate record values", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE INDEX test ON person COLUMNS account, email UNIQUE; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="info@demo.com"; - SELECT * FROM person ORDER BY meta.id; - DEFINE INDEX test ON person COLUMNS account, email UNIQUE; - UPDATE person:one SET account="demo", email="info@demo.com"; - UPDATE person:two SET account="demo", email="info@demo.com"; - UPDATE person:tre SET account="demo", email="info@demo.com"; - SELECT * FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 0) - So(res[3].Status, ShouldEqual, "ERR_IX") - So(res[4].Result, ShouldHaveLength, 0) - So(res[4].Status, ShouldEqual, "ERR_IX") - So(res[5].Result, ShouldHaveLength, 1) - So(data.Consume(res[5].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 1) - So(res[7].Status, ShouldEqual, "OK") - So(res[8].Result, ShouldHaveLength, 0) - So(res[8].Status, ShouldEqual, "ERR_IX") - So(res[9].Result, ShouldHaveLength, 0) - So(res[9].Status, ShouldEqual, "ERR_IX") - So(res[10].Result, ShouldHaveLength, 1) - So(data.Consume(res[10].Result[0]).Get("id").Data(), ShouldResemble, &sql.Thing{"person", "one"}) - - }) - -} diff --git a/db/delete.go b/db/delete.go deleted file mode 100644 index 9f86d1cd..00000000 --- a/db/delete.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeDelete(ctx context.Context, stm *sql.DeleteStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - var what sql.Exprs - - for _, val := range stm.What { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - what = append(what, w) - } - - i := newIterator(e, ctx, stm, false) - - for _, w := range what { - - switch what := w.(type) { - - default: - return nil, fmt.Errorf("Can not execute DELETE query using value '%v'", what) - - case *sql.Table: - key := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: what.TB} - i.processTable(ctx, key) - - case *sql.Ident: - key := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: what.VA} - i.processTable(ctx, key) - - case *sql.Thing: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: what.ID} - i.processThing(ctx, key) - - case *sql.Model: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processModel(ctx, key, what) - - case *sql.Batch: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processBatch(ctx, key, what) - - // Result of subquery - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, what) - - // Result of subquery with LIMIT 1 - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, []interface{}{what}) - - } - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchDelete(ctx context.Context, stm *sql.DeleteStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeDelete(ctx, stm) - if err != nil { - return nil, err - } - - switch len(out) { - case 1: - return data.Consume(out).Get(docKeyOne, docKeyId).Data(), nil - default: - return data.Consume(out).Get(docKeyAll, docKeyId).Data(), nil - } - -} - -func (d *document) runDelete(ctx context.Context, stm *sql.DeleteStatement) (interface{}, error) { - - var ok bool - var err error - var met = _DELETE - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.lock(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.val.Exi() == false { - return nil, nil - } - - if ok, err = d.check(ctx, stm.Cond); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.erase(); err != nil { - return nil, err - } - - if err = d.purgeIndex(ctx); err != nil { - return nil, err - } - - if err = d.purgeThing(ctx); err != nil { - return nil, err - } - - if err = d.table(ctx, met); err != nil { - return nil, err - } - - if err = d.lives(ctx, met); err != nil { - return nil, err - } - - if err = d.event(ctx, met); err != nil { - return nil, err - } - - return d.yield(ctx, stm, stm.Echo) - -} diff --git a/db/delete_test.go b/db/delete_test.go deleted file mode 100644 index b523a8a7..00000000 --- a/db/delete_test.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestDelete(t *testing.T) { - - Convey("Delete with invalid value", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DELETE 1; - DELETE "one"; - DELETE ["many"]; - DELETE [{value:"one"}]; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "ERR") - So(res[1].Detail, ShouldEqual, "Can not execute DELETE query using value '1'") - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Can not execute DELETE query using value 'one'") - So(res[3].Status, ShouldEqual, "ERR") - So(res[3].Detail, ShouldEqual, "Can not execute DELETE query using value '[many]'") - So(res[4].Status, ShouldEqual, "ERR") - So(res[4].Detail, ShouldEqual, "Can not execute DELETE query using value '[map[value:one]]'") - - }) - - Convey("Delete records using `table`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:10|; - SELECT * FROM person; - DELETE person; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - So(res[4].Result, ShouldHaveLength, 0) - - }) - - Convey("Delete specific record using `thing`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - SELECT * FROM person; - DELETE person:test; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 0) - - }) - - Convey("Delete unique records using `batch`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person; - DELETE batch("person", ["1", "2", "person:3"]); - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 0) - So(res[4].Result, ShouldHaveLength, 7) - - }) - - Convey("Delete unique records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person; - DELETE |person:1..5|; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 0) - So(res[4].Result, ShouldHaveLength, 5) - - }) - - Convey("Deleting with a timeout of 1ns returns an error", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DELETE |person:1..1000| TIMEOUT 1ns; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 0) - So(res[2].Result, ShouldHaveLength, 0) - So(res[1].Status, ShouldEqual, "ERR_TO") - So(res[1].Detail, ShouldEqual, "Query timeout of 1ns exceeded") - - }) - -} diff --git a/db/document.go b/db/document.go deleted file mode 100644 index 6f138910..00000000 --- a/db/document.go +++ /dev/null @@ -1,444 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/indx" - "github.com/surrealdb/surrealdb/util/keys" -) - -type document struct { - i *iterator - id *sql.Thing - enc []byte - key *keys.Thing - val kvs.KV - lck bool - doc *data.Doc - initial *data.Doc - current *data.Doc - changed bool -} - -func newDocument(i *iterator, key *keys.Thing, val kvs.KV, doc *data.Doc) (d *document) { - - d = documentPool.Get().(*document) - - d.i = i - d.id = nil - d.enc = nil - d.key = key - d.val = val - d.doc = doc - d.lck = false - - return - -} - -func (d *document) close() { - documentPool.Put(d) -} - -func (d *document) erase() (err error) { - d.changed, d.current = true, data.Consume(nil) - return -} - -func (d *document) query(ctx context.Context, stm sql.Statement) (val interface{}, err error) { - - defer func() { - - if r := recover(); r != nil { - var ok bool - if err, ok = r.(error); !ok { - err = fmt.Errorf("%v", r) - } - } - - d.ulock(ctx) - - d.close() - - }() - - switch stm := stm.(type) { - default: - return nil, nil - case *sql.SelectStatement: - return d.runSelect(ctx, stm) - case *sql.CreateStatement: - return d.runCreate(ctx, stm) - case *sql.UpdateStatement: - return d.runUpdate(ctx, stm) - case *sql.DeleteStatement: - return d.runDelete(ctx, stm) - case *sql.RelateStatement: - return d.runRelate(ctx, stm) - case *sql.InsertStatement: - return d.runInsert(ctx, stm) - case *sql.UpsertStatement: - return d.runUpsert(ctx, stm) - } - -} - -func (d *document) init(ctx context.Context) (err error) { - - // A table of records were requested - // so we have the values, but no key - // yet, so we need to decode the KV - // store key into a Thing key. - - if d.key == nil && d.val != nil { - d.enc = d.val.Key() - if val, ok := keyCache.Get(d.val.Key()); ok { - d.key = val.(*keys.Thing) - } else { - d.key = &keys.Thing{} - d.key.Decode(d.enc) - keyCache.Set(d.val.Key(), d.key, 0) - } - } - - return - -} - -func (d *document) lock(ctx context.Context) (err error) { - - if d.key != nil { - d.lck = true - d.i.e.lock.Lock(ctx, d.key) - } - - return - -} - -func (d *document) ulock(ctx context.Context) (err error) { - - if d.key != nil && d.lck { - d.lck = false - d.i.e.lock.Unlock(ctx, d.key) - } - - return - -} - -func (d *document) setup(ctx context.Context) (err error) { - - // A specific record has been requested - // and we have a key, but no value has - // been loaded yet, so the record needs - // to be loaded from the KV store. - - if d.key != nil && d.val == nil { - d.enc = d.key.Encode() - d.val, err = d.i.e.tx.Get(ctx, d.i.versn, d.enc) - if err != nil { - return - } - } - - // A subquery or data param has been - // loaded, and we might not have a key - // or a value, so let's load the data - // into a document, so that we can - // maniuplate the virtual document. - - if d.doc != nil { - d.initial = d.doc - d.current = d.doc - } - - // The requested record has been loaded - // from the KV store (and not from a - // subquery or data variable), but does - // not exist. So we'll create a document - // for processing any record changes. - - if d.doc == nil && d.val != nil && d.val.Exi() == false { - d.initial = data.New() - d.current = data.New() - } - - // The requested record has been loaded - // from the KV store (and not from a - // subquery or data variable). So we'll - // load the KV data into a document for - // processing any record changes. - - if d.doc == nil && d.val != nil && d.val.Exi() == true { - if val, ok := valCache.Get(d.val.Val()); ok { - d.initial = val.(*data.Doc) - d.current = d.initial - } else { - d.initial = data.New().Decode(d.val.Val()) - d.current = d.initial - valCache.Set(d.val.Val(), d.current, 0) - } - } - - // Finally if we are dealing with a record - // which is not data from the result of a - // subquery, then generate the ID. - - if d.key != nil { - d.id = sql.NewThing(d.key.TB, d.key.ID) - } - - return - -} - -func (d *document) forced(ctx context.Context) bool { - if val := ctx.Value(ctxKeyForce); val != nil { - return val.(bool) - } - return false -} - -func (d *document) hasChanged(ctx context.Context) bool { - return d.initial.Same(d.current) == false -} - -func (d *document) shouldDrop(ctx context.Context) (bool, error) { - - // Check whether it is specified - // that the table should drop - // writes, and if so, then return. - - tb, err := d.i.e.tx.GetTB(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return false, err - } - - return tb.Drop, err - -} - -func (d *document) shouldVersn(ctx context.Context) (bool, error) { - - // Check whether it is specified - // that the table should keep - // all document versions. - - tb, err := d.i.e.tx.GetTB(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return false, err - } - - return tb.Vers, err - -} - -func (d *document) storeThing(ctx context.Context) (err error) { - - defer d.ulock(ctx) - - // Check that the record has been - // changed, and if not, return. - - if !d.changed { - return - } - - // Check that the table should - // drop data being written. - - if ok, err := d.shouldDrop(ctx); ok { - return err - } - - // Write the value to the data - // layer and return any errors. - - if ok, err := d.shouldVersn(ctx); err != nil { - return err - } else if ok == true { - _, err = d.i.e.tx.Put(ctx, d.i.e.time.UnixNano(), d.enc, d.current.Encode()) - } else if ok == false { - _, err = d.i.e.tx.Put(ctx, 0, d.enc, d.current.Encode()) - } - - return - -} - -func (d *document) purgeThing(ctx context.Context) (err error) { - - defer d.ulock(ctx) - - // Check that the table should - // drop data being written. - - if ok, err := d.shouldDrop(ctx); ok { - return err - } - - // Reset the item by writing a - // nil value to the storage. - - if ok, err := d.shouldVersn(ctx); err != nil { - return err - } else if ok == true { - _, err = d.i.e.tx.Put(ctx, d.i.e.time.UnixNano(), d.enc, nil) - } else if ok == false { - _, err = d.i.e.tx.Clr(ctx, d.enc) - } - - return - -} - -func (d *document) storeIndex(ctx context.Context) (err error) { - - // Check if this query has been run - // in forced mode, or return. - - forced := d.forced(ctx) - - // Check that the rcord has been - // changed, and if not, return. - - if !forced && !d.changed { - return - } - - // Check that the table should - // drop data being written. - - if ok, err := d.shouldDrop(ctx); ok { - return err - } - - // Get the index values specified - // for this table, loop through - // them, and compute the changes. - - ixs, err := d.i.e.tx.AllIX(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - for _, ix := range ixs { - - del := indx.Build(ix.Cols, d.initial) - add := indx.Build(ix.Cols, d.current) - - if !forced { - del, add = indx.Diff(del, add) - } - - if ix.Uniq == true { - for _, f := range del { - enfd := data.Consume(f).Encode() - didx := &keys.Index{KV: d.key.KV, NS: d.key.NS, DB: d.key.DB, TB: d.key.TB, IX: ix.Name.VA, FD: enfd} - d.i.e.tx.DelC(ctx, 0, didx.Encode(), d.id.Bytes()) - } - for _, f := range add { - enfd := data.Consume(f).Encode() - aidx := &keys.Index{KV: d.key.KV, NS: d.key.NS, DB: d.key.DB, TB: d.key.TB, IX: ix.Name.VA, FD: enfd} - if _, err = d.i.e.tx.PutC(ctx, 0, aidx.Encode(), d.id.Bytes(), nil); err != nil { - return &IndexError{tb: d.key.TB, name: ix.Name, cols: ix.Cols, vals: f} - } - } - } - - if ix.Uniq == false { - for _, f := range del { - enfd := data.Consume(f).Encode() - didx := &keys.Point{KV: d.key.KV, NS: d.key.NS, DB: d.key.DB, TB: d.key.TB, IX: ix.Name.VA, FD: enfd, ID: d.key.ID} - d.i.e.tx.DelC(ctx, 0, didx.Encode(), d.id.Bytes()) - } - for _, f := range add { - enfd := data.Consume(f).Encode() - aidx := &keys.Point{KV: d.key.KV, NS: d.key.NS, DB: d.key.DB, TB: d.key.TB, IX: ix.Name.VA, FD: enfd, ID: d.key.ID} - if _, err = d.i.e.tx.PutC(ctx, 0, aidx.Encode(), d.id.Bytes(), nil); err != nil { - return &IndexError{tb: d.key.TB, name: ix.Name, cols: ix.Cols, vals: f} - } - } - } - - } - - return - -} - -func (d *document) purgeIndex(ctx context.Context) (err error) { - - // Check if this query has been run - // in forced mode, or return. - - forced := d.forced(ctx) - - // Check that the rcord has been - // changed, and if not, return. - - if !forced && !d.changed { - return - } - - // Check that the table should - // drop data being written. - - if ok, err := d.shouldDrop(ctx); ok { - return err - } - - // Get the index values specified - // for this table, loop through - // them, and compute the changes. - - ixs, err := d.i.e.tx.AllIX(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - for _, ix := range ixs { - - del := indx.Build(ix.Cols, d.initial) - - if ix.Uniq == true { - for _, f := range del { - enfd := data.Consume(f).Encode() - didx := &keys.Index{KV: d.key.KV, NS: d.key.NS, DB: d.key.DB, TB: d.key.TB, IX: ix.Name.VA, FD: enfd} - d.i.e.tx.DelC(ctx, 0, didx.Encode(), d.id.Bytes()) - } - } - - if ix.Uniq == false { - for _, f := range del { - enfd := data.Consume(f).Encode() - aidx := &keys.Point{KV: d.key.KV, NS: d.key.NS, DB: d.key.DB, TB: d.key.TB, IX: ix.Name.VA, FD: enfd, ID: d.key.ID} - d.i.e.tx.DelC(ctx, 0, aidx.Encode(), d.id.Bytes()) - } - } - - } - - return - -} diff --git a/db/error.go b/db/error.go deleted file mode 100644 index 7474784a..00000000 --- a/db/error.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - "time" - - "github.com/surrealdb/surrealdb/sql" -) - -// LiveError occurs when a query can not be run. -type LiveError struct{} - -// Error returns the string representation of the error. -func (e *LiveError) Error() string { - return fmt.Sprintf("Unable to perform live query.") -} - -// TimerError occurs when a query times out. -type TimerError struct { - timer time.Duration -} - -// Error returns the string representation of the error. -func (e *TimerError) Error() string { - return fmt.Sprintf("Query timeout of %v exceeded", e.timer) -} - -// TableError occurs when an table value is unable to be written. -type TableError struct { - table string -} - -// Error returns the string representation of the error. -func (e *TableError) Error() string { - return fmt.Sprintf("Unable to write to the '%v' table while it is setup as a view", e.table) -} - -// QueryError represents an error that occured when switching access. -type QueryError struct{} - -// Error returns the string representation of the error. -func (e *QueryError) Error() string { - return fmt.Sprint("You don't have permission to perform this query type") -} - -// BlankError represents an error that occured when switching access. -type BlankError struct{} - -// Error returns the string representation of the error. -func (e *BlankError) Error() string { - return fmt.Sprint("You need to specify a namespace and a database to use") -} - -// PermsError occurs when a table query is not allowed. -type PermsError struct { - table string -} - -// Error returns the string representation of the error. -func (e *PermsError) Error() string { - return fmt.Sprintf("You don't have permission to perform this query on the '%v' table", e.table) -} - -// LimitError occurs when a 'limit' expression is invalid. -type LimitError struct { - found interface{} -} - -// Error returns the string representation of the error. -func (e *LimitError) Error() string { - return fmt.Sprintf("Found '%v' but LIMIT expression must be a number", e.found) -} - -// StartError occurs when a 'start' expression is invalid. -type StartError struct { - found interface{} -} - -// Error returns the string representation of the error. -func (e *StartError) Error() string { - return fmt.Sprintf("Found '%v' but START expression must be a number", e.found) -} - -// VersnError occurs when a 'version' expression is invalid. -type VersnError struct { - found interface{} -} - -// Error returns the string representation of the error. -func (e *VersnError) Error() string { - return fmt.Sprintf("Found '%v' but VERSION expression must be a date or time", e.found) -} - -// ExistError occurs when a record already exists. -type ExistError struct { - exist *sql.Thing -} - -// Error returns the string representation of the error. -func (e *ExistError) Error() string { - return fmt.Sprintf("Database record '%v' already exists", e.exist) -} - -// FieldError occurs when a field does not conform to the specified assertion. -type FieldError struct { - field interface{} - found interface{} - check interface{} -} - -// Error returns the string representation of the error. -func (e *FieldError) Error() string { - return fmt.Sprintf("Found '%v' for field '%v' but field must conform to: %s", e.found, e.field, e.check) -} - -// IndexError occurs when an index value is unable to be written. -type IndexError struct { - tb string - name *sql.Ident - cols sql.Idents - vals []interface{} -} - -// Error returns the string representation of the error. -func (e *IndexError) Error() string { - return fmt.Sprintf("Duplicate entry for [%v] wth values %v in index '%s' on '%s'", e.cols, e.vals, e.name, e.tb) -} diff --git a/db/event.go b/db/event.go deleted file mode 100644 index 1cbac236..00000000 --- a/db/event.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/util/data" -) - -// Event checks if any triggers are specified for this -// table, and executes them in name order. -func (d *document) event(ctx context.Context, met method) (err error) { - - if !d.i.e.opts.events { - return nil - } - - // Check if this query has been run - // in forced mode, because of an - // index or foreign table update. - - forced := d.forced(ctx) - - // If this document has not changed - // then there is no need to perform - // any registered events. - - if !forced && !d.changed { - return nil - } - - // Get the event values specified - // for this table, loop through - // them, and compute the events. - - evs, err := d.i.e.tx.AllEV(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - if len(evs) > 0 { - - kind := "" - - switch met { - case _CREATE: - kind = "CREATE" - case _UPDATE: - kind = "UPDATE" - case _DELETE: - kind = "DELETE" - } - - var id = d.i.e.id - d.i.e.id = d.i.e.id + "-bg" - defer func() { d.i.e.id = id }() - - vars := data.New() - vars.Set(d.id, varKeyThis) - vars.Set(kind, varKeyMethod) - vars.Set(d.current.Data(), varKeyAfter) - vars.Set(d.initial.Data(), varKeyBefore) - ctx = context.WithValue(ctx, ctxKeySpec, vars) - - ctx = context.WithValue(ctx, ctxKeyKind, cnf.AuthDB) - - for _, ev := range evs { - - val, err := d.i.e.fetch(ctx, ev.When, d.current) - if err != nil { - return err - } - - switch v := val.(type) { - case bool: - switch v { - case true: - _, err = d.i.e.fetch(ctx, ev.Then, d.current) - if err != nil { - return err - } - } - } - - } - - } - - return - -} diff --git a/db/executor.go b/db/executor.go deleted file mode 100644 index fa8b462c..00000000 --- a/db/executor.go +++ /dev/null @@ -1,543 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "sync" - "time" - - "context" - - "runtime/debug" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/log" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" -) - -type executor struct { - id string - ns string - db string - tx *txn.TX - err error - buf []*Response - time time.Time - lock *mutex - opts *options - data sync.Map - send chan *Response -} - -func newExecutor(id, ns, db string) (e *executor) { - - e = executorPool.Get().(*executor) - - e.id = id - e.ns = ns - e.db = db - - e.tx = nil - e.err = nil - e.buf = nil - - e.data = sync.Map{} - - e.opts = newOptions() - - e.send = make(chan *Response) - - return - -} - -func (e *executor) execute(ctx context.Context, ast *sql.Query) { - - // Ensure that the executor is added back into - // the executor pool when the executor has - // finished processing the request. - - defer executorPool.Put(e) - - // Ensure that the query responses channel is - // closed when the full query has been processed - // and dealt with. - - defer close(e.send) - - // If we are making use of a global transaction - // which is not committed at the end of the - // query set, then cancel the transaction. - - defer func() { - if e.tx != nil { - e.tx.Cancel() - clear(e.id) - e.tx = nil - } - }() - - // If we have panicked during query execution - // then ensure that we recover from the error - // and print the error to the log. - - defer func() { - if err := recover(); err != nil { - if log.IsError() { - log.WithPrefix(logKeyDB).WithFields(map[string]interface{}{ - logKeyId: e.id, - logKeyStack: string(debug.Stack()), - logKeyFibre: ctx.Value(ctxKeyFibre).(*fibre.Context), - }).Errorln(err) - } - } - }() - - // Loop over the defined query statements and - // process them, while listening for the quit - // channel to see if the client has gone away. - - for _, stm := range ast.Statements { - select { - case <-ctx.Done(): - return - default: - e.conduct(ctx, stm) - } - } - -} - -func (e *executor) conduct(ctx context.Context, stm sql.Statement) { - - var rsp *Response - var res []interface{} - - // If we are not inside a global transaction - // then reset the error to nil so that the - // next statement is not ignored. - - if e.tx == nil { - e.err = nil - } - - // Check to see if the current statement is - // a TRANSACTION statement, and if it is - // then deal with it and move on to the next. - - switch stm.(type) { - case *sql.BeginStatement: - e.err = e.begin(ctx, true) - if e.err != nil { - clear(e.id) - } - return - case *sql.CancelStatement: - e.err = e.cancel(e.send) - if e.err != nil { - clear(e.id) - } else { - clear(e.id) - } - return - case *sql.CommitStatement: - e.err = e.commit(e.send) - if e.err != nil { - clear(e.id) - } else { - flush(e.id) - } - return - } - - // If an error has occured and we are inside - // a global transaction, then ignore all - // subsequent statements in the transaction. - - if e.err == nil { - res, e.err = e.operate(ctx, stm) - } else { - res, e.err = []interface{}{}, errQueryNotExecuted - } - - // Generate the response - - rsp = &Response{ - Time: time.Since(e.time).String(), - Status: status(e.err), - Detail: detail(e.err), - Result: append([]interface{}{}, res...), - } - - // Log the sql statement along with the - // query duration time, and mark it as - // an error if the query failed. - - switch e.err.(type) { - default: - if log.IsDebug() { - log.WithPrefix(logKeySql).WithFields(map[string]interface{}{ - logKeyId: e.id, - logKeyNS: e.ns, - logKeyDB: e.db, - logKeyKind: ctx.Value(ctxKeyKind), - logKeyVars: ctx.Value(ctxKeyVars), - logKeyTime: time.Since(e.time).String(), - logKeyFibre: ctx.Value(ctxKeyFibre).(*fibre.Context), - }).Debugln(stm) - } - case error: - if log.IsError() { - log.WithPrefix(logKeySql).WithFields(map[string]interface{}{ - logKeyId: e.id, - logKeyNS: e.ns, - logKeyDB: e.db, - logKeyKind: ctx.Value(ctxKeyKind), - logKeyVars: ctx.Value(ctxKeyVars), - logKeyTime: time.Since(e.time).String(), - logKeyFibre: ctx.Value(ctxKeyFibre).(*fibre.Context), - logKeyError: detail(e.err), - }).Errorln(stm) - } - } - - // If we are not inside a global transaction - // then we can output the statement response - // immediately to the channel. - - if e.tx == nil { - e.send <- rsp - } - - // If we are inside a global transaction we - // must buffer the responses for output at - // the end of the transaction. - - if e.tx != nil { - switch stm.(type) { - case *sql.ReturnStatement: - for i := len(e.buf) - 1; i >= 0; i-- { - e.buf[len(e.buf)-1] = nil - e.buf = e.buf[:len(e.buf)-1] - } - e.buf = append(e.buf, rsp) - default: - e.buf = append(e.buf, rsp) - } - } - -} - -func (e *executor) operate(ctx context.Context, stm sql.Statement) (res []interface{}, err error) { - - var loc bool - var trw bool - var canc context.CancelFunc - - // If we are not inside a global transaction - // then grab a new transaction, ensuring that - // it is closed at the end. - - if e.tx == nil { - - switch stm := stm.(type) { - case sql.WriteableStatement: - loc, trw = true, stm.Writeable() - default: - loc, trw = true, false - } - - err = e.begin(ctx, trw) - if err != nil { - return - } - - } - - // Mark the beginning of this statement so we - // can monitor the running time, and ensure - // it runs no longer than specified. - - if cnf.Settings.Query.Timeout > 0 { - if perm(ctx) != cnf.AuthKV { - ctx, canc = context.WithTimeout(ctx, cnf.Settings.Query.Timeout) - defer func() { - if tim := ctx.Err(); err == nil && tim != nil { - res, err = nil, &TimerError{timer: cnf.Settings.Query.Timeout} - } - canc() - }() - } - } - - // Mark the beginning of this statement so we - // can monitor the running time, and ensure - // it runs no longer than specified. - - if stm, ok := stm.(sql.KillableStatement); ok { - if dur := stm.Duration(); dur > 0 { - ctx, canc = context.WithTimeout(ctx, dur) - defer func() { - if tim := ctx.Err(); err == nil && tim != nil { - res, err = nil, &TimerError{timer: dur} - } - canc() - }() - } - } - - // Execute the defined statement, receiving the - // result set, and any errors which occured - // while processing the query. - - switch stm := stm.(type) { - - case *sql.OptStatement: - res, err = e.executeOpt(ctx, stm) - - case *sql.UseStatement: - res, err = e.executeUse(ctx, stm) - - case *sql.RunStatement: - res, err = e.executeRun(ctx, stm) - - case *sql.InfoStatement: - res, err = e.executeInfo(ctx, stm) - - case *sql.LetStatement: - res, err = e.executeLet(ctx, stm) - case *sql.ReturnStatement: - res, err = e.executeReturn(ctx, stm) - - case *sql.LiveStatement: - res, err = e.executeLive(ctx, stm) - case *sql.KillStatement: - res, err = e.executeKill(ctx, stm) - - case *sql.IfelseStatement: - res, err = e.executeIfelse(ctx, stm) - case *sql.SelectStatement: - res, err = e.executeSelect(ctx, stm) - case *sql.CreateStatement: - res, err = e.executeCreate(ctx, stm) - case *sql.UpdateStatement: - res, err = e.executeUpdate(ctx, stm) - case *sql.DeleteStatement: - res, err = e.executeDelete(ctx, stm) - case *sql.RelateStatement: - res, err = e.executeRelate(ctx, stm) - - case *sql.InsertStatement: - res, err = e.executeInsert(ctx, stm) - case *sql.UpsertStatement: - res, err = e.executeUpsert(ctx, stm) - - case *sql.DefineNamespaceStatement: - res, err = e.executeDefineNamespace(ctx, stm) - case *sql.RemoveNamespaceStatement: - res, err = e.executeRemoveNamespace(ctx, stm) - - case *sql.DefineDatabaseStatement: - res, err = e.executeDefineDatabase(ctx, stm) - case *sql.RemoveDatabaseStatement: - res, err = e.executeRemoveDatabase(ctx, stm) - - case *sql.DefineLoginStatement: - res, err = e.executeDefineLogin(ctx, stm) - case *sql.RemoveLoginStatement: - res, err = e.executeRemoveLogin(ctx, stm) - - case *sql.DefineTokenStatement: - res, err = e.executeDefineToken(ctx, stm) - case *sql.RemoveTokenStatement: - res, err = e.executeRemoveToken(ctx, stm) - - case *sql.DefineScopeStatement: - res, err = e.executeDefineScope(ctx, stm) - case *sql.RemoveScopeStatement: - res, err = e.executeRemoveScope(ctx, stm) - - case *sql.DefineTableStatement: - res, err = e.executeDefineTable(ctx, stm) - case *sql.RemoveTableStatement: - res, err = e.executeRemoveTable(ctx, stm) - - case *sql.DefineEventStatement: - res, err = e.executeDefineEvent(ctx, stm) - case *sql.RemoveEventStatement: - res, err = e.executeRemoveEvent(ctx, stm) - - case *sql.DefineFieldStatement: - res, err = e.executeDefineField(ctx, stm) - case *sql.RemoveFieldStatement: - res, err = e.executeRemoveField(ctx, stm) - - case *sql.DefineIndexStatement: - res, err = e.executeDefineIndex(ctx, stm) - case *sql.RemoveIndexStatement: - res, err = e.executeRemoveIndex(ctx, stm) - - } - - // If the context is already closed or failed, - // then ignore this result, clear all queued - // changes, and reset the transaction. - - select { - - case <-ctx.Done(): - - e.tx.Cancel() - clear(e.id) - e.tx = nil - - default: - - // If this is a local transaction for only the - // current statement, then commit or cancel - // depending on the result error. - - if loc && e.tx.Closed() == false { - - // If there was an error with the query - // then clear the queued changes and - // return immediately. - - if err != nil { - e.tx.Cancel() - clear(e.id) - e.tx = nil - return - } - - // Otherwise check if this is a read or - // a write transaction, and attempt to - // Cancel or Commit, returning any errors. - - if !trw { - if err = e.tx.Cancel(); err != nil { - clear(e.id) - e.tx = nil - } else { - clear(e.id) - e.tx = nil - } - } else { - if err = e.tx.Commit(); err != nil { - clear(e.id) - e.tx = nil - } else { - flush(e.id) - e.tx = nil - } - } - - } - - } - - return - -} - -func (e *executor) begin(ctx context.Context, rw bool) (err error) { - e.tx, err = txn.New(ctx, rw) - e.time = time.Now() - e.lock = new(mutex) - return -} - -func (e *executor) cancel(chn chan<- *Response) (err error) { - - defer func() { - e.tx.Cancel() - e.tx = nil - e.buf = nil - e.err = nil - }() - - for _, v := range e.buf { - v.Time = time.Since(e.time).String() - v.Status = "ERR" - v.Result = []interface{}{} - v.Detail = "Transaction cancelled" - chn <- v - } - - return - -} - -func (e *executor) commit(chn chan<- *Response) (err error) { - - defer func() { - e.tx.Cancel() - e.tx = nil - e.buf = nil - e.err = nil - }() - - if e.err != nil { - err = e.tx.Cancel() - } else { - err = e.tx.Commit() - } - - for _, v := range e.buf { - if err != nil { - v.Time = time.Since(e.time).String() - v.Status = "ERR" - v.Result = []interface{}{} - v.Detail = "Transaction failed: " + err.Error() - } - chn <- v - } - - return - -} - -func status(e error) (s string) { - switch e.(type) { - default: - return "OK" - case *kvs.DBError: - return "ERR_DB" - case *PermsError: - return "ERR_PE" - case *ExistError: - return "ERR_EX" - case *FieldError: - return "ERR_FD" - case *IndexError: - return "ERR_IX" - case *TimerError: - return "ERR_TO" - case error: - return "ERR" - } -} - -func detail(e error) (s string) { - switch err := e.(type) { - default: - return - case error: - return err.Error() - } -} diff --git a/db/export.go b/db/export.go deleted file mode 100644 index ce37d541..00000000 --- a/db/export.go +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - "math" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" -) - -var sep = ` --- ------------------------------ --- %s --- ------------------------------ -` - -func export(c *fibre.Context, NS, DB string) error { - - w := c.Response() - - ctx := c.Context() - - exe := newExecutor(NIL, NS, DB) - - err := exe.begin(ctx, false) - - defer executorPool.Put(exe) - - // ------------------------------ - // Options - // ------------------------------ - - fmt.Fprintf(w, sep, "OPTION") - fmt.Fprintln(w) - fmt.Fprintf(w, "OPTION IMPORT;\n") - - // ------------------------------ - // Tokens - // ------------------------------ - - dts, err := exe.tx.AllDT(ctx, NS, DB) - if err != nil { - return err - } - - if len(dts) > 0 { - fmt.Fprintf(w, sep, "TOKENS") - fmt.Fprintln(w) - for _, v := range dts { - fmt.Fprintf(w, "%s;\n", v) - } - } - - // ------------------------------ - // Logins - // ------------------------------ - - dus, err := exe.tx.AllDU(ctx, NS, DB) - if err != nil { - return err - } - - if len(dus) > 0 { - fmt.Fprintf(w, sep, "LOGINS") - fmt.Fprintln(w) - for _, v := range dus { - fmt.Fprintf(w, "%s;\n", v) - } - } - - // ------------------------------ - // Scopes - // ------------------------------ - - scs, err := exe.tx.AllSC(ctx, NS, DB) - if err != nil { - return err - } - - if len(scs) > 0 { - - fmt.Fprintf(w, sep, "SCOPES") - - fmt.Fprintln(w) - - for _, v := range scs { - - fmt.Fprintf(w, "%s;\n", v) - - // ------------------------------ - // Tokens - // ------------------------------ - - sct, err := exe.tx.AllST(ctx, NS, DB, v.Name.VA) - if err != nil { - return err - } - - if len(sct) > 0 { - fmt.Fprintln(w) - for _, v := range sct { - fmt.Fprintf(w, "%s;\n", v) - } - fmt.Fprintln(w) - } - - } - - } - - // ------------------------------ - // Tables - // ------------------------------ - - tbs, err := exe.tx.AllTB(ctx, NS, DB) - if err != nil { - return err - } - - for _, TB := range tbs { - - fmt.Fprintf(w, sep, "TABLE: "+TB.Name.VA) - - // ------------------------------ - // Remove - // ------------------------------ - - fmt.Fprintln(w) - - fmt.Fprintf(w, "%s;\n", &sql.RemoveTableStatement{ - What: sql.Tables{&sql.Table{TB.Name.VA}}, - }) - - // ------------------------------ - // Define - // ------------------------------ - - fmt.Fprintln(w) - - fmt.Fprintf(w, "%s;\n", TB) - - // ------------------------------ - // Events - // ------------------------------ - - evs, err := exe.tx.AllEV(ctx, NS, DB, TB.Name.VA) - if err != nil { - return err - } - - if len(evs) > 0 { - fmt.Fprintln(w) - for _, v := range evs { - fmt.Fprintf(w, "%s;\n", v) - } - } - - // ------------------------------ - // Fields - // ------------------------------ - - fds, err := exe.tx.AllFD(ctx, NS, DB, TB.Name.VA) - if err != nil { - return err - } - - if len(fds) > 0 { - fmt.Fprintln(w) - for _, v := range fds { - fmt.Fprintf(w, "%s;\n", v) - } - } - - // ------------------------------ - // Indexes - // ------------------------------ - - ixs, err := exe.tx.AllIX(ctx, NS, DB, TB.Name.VA) - if err != nil { - return err - } - - if len(ixs) > 0 { - fmt.Fprintln(w) - for _, v := range ixs { - fmt.Fprintf(w, "%s;\n", v) - } - } - - } - - // ------------------------------ - // BEGIN - // ------------------------------ - - fmt.Fprintf(w, sep, "TRANSACTION") - fmt.Fprintln(w) - fmt.Fprintf(w, "BEGIN TRANSACTION;\n") - - // ------------------------------ - // DATA - // ------------------------------ - -TB: - for _, TB := range tbs { - - fmt.Fprintf(w, sep, "TABLE DATA: "+TB.Name.VA) - fmt.Fprintln(w) - - beg := &keys.Thing{KV: cnf.Settings.DB.Base, NS: NS, DB: DB, TB: TB.Name.VA, ID: keys.Ignore} - end := &keys.Thing{KV: cnf.Settings.DB.Base, NS: NS, DB: DB, TB: TB.Name.VA, ID: keys.Suffix} - - min, max := beg.Encode(), end.Encode() - - for x := 0; ; x = 1 { - - var err error - var vls []kvs.KV - - if TB.Vers { - vls, err = exe.tx.AllR(ctx, min, max, 10000) - } else { - vls, err = exe.tx.GetR(ctx, math.MaxInt64, min, max, 10000) - } - - if err != nil { - return err - } - - // If there are no further records - // fetched from the data layer, then - // return out of this loop iteration. - - if x >= len(vls) { - continue TB - } - - // If there is at least 1 key-value - // then loop over all the items and - // process the records. - - n := data.New() - - for _, kv := range vls { - - k := &keys.Thing{} - k.Decode(kv.Key()) - - v := kv.Ver() - - if kv.Exi() { - - n = data.New().Decode(kv.Val()) - - j, _ := n.MarshalJSON() - - if TB.Vers { - fmt.Fprintf(w, "UPDATE ⟨%s⟩:⟨%s⟩ CONTENT %s VERSION %d;\n", k.TB, k.ID, j, v) - } else { - fmt.Fprintf(w, "UPDATE ⟨%s⟩:⟨%s⟩ CONTENT %s;\n", k.TB, k.ID, j) - } - - } else { - - if TB.Vers { - fmt.Fprintf(w, "DELETE ⟨%s⟩:⟨%s⟩ VERSION %d;\n", k.TB, k.ID, v) - } else { - fmt.Fprintf(w, "DELETE ⟨%s⟩:⟨%s⟩;\n", k.TB, k.ID) - } - - } - - } - - // When we loop around, we will use - // the key of the last retrieved key - // to perform the next range request. - - beg.Decode(vls[len(vls)-1].Key()) - - min = append(beg.Encode(), byte(0)) - - } - - } - - // ------------------------------ - // COMMIT - // ------------------------------ - - fmt.Fprintf(w, sep, "TRANSACTION") - fmt.Fprintln(w) - fmt.Fprintf(w, "COMMIT TRANSACTION;\n") - - return nil - -} diff --git a/db/fetch.go b/db/fetch.go deleted file mode 100644 index dc5c82dd..00000000 --- a/db/fetch.go +++ /dev/null @@ -1,1461 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - "math" - "reflect" - "regexp" - "strconv" - "strings" - "time" - - "golang.org/x/text/language" - "golang.org/x/text/search" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/geof" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/deep" - "github.com/surrealdb/surrealdb/util/fncs" -) - -var ign = data.New() - -func (e *executor) fetch(ctx context.Context, val interface{}, doc *data.Doc) (out interface{}, err error) { - - switch val := val.(type) { - default: - return val, nil - case *sql.Null: - return nil, nil - case *sql.Value: - return val.VA, nil - case []byte: - return string(val), nil - case int: - return float64(val), nil - case int8: - return float64(val), nil - case int16: - return float64(val), nil - case int32: - return float64(val), nil - case int64: - return float64(val), nil - case uint: - return float64(val), nil - case uint16: - return float64(val), nil - case uint32: - return float64(val), nil - case uint64: - return float64(val), nil - case float32: - return float64(val), nil - case float64: - return float64(val), nil - case []interface{}: - return deep.Copy(val), nil - case map[string]interface{}: - return deep.Copy(val), nil - - case *sql.Regex: - - return regexp.Compile(val.VA) - - case *sql.Ident: - - switch { - default: - return val, nil - case doc == ign: - return val, queryIdentFailed - case doc != nil: - - fnc := func(key string, val interface{}, path []string) interface{} { - if len(path) > 0 { - switch res := val.(type) { - case []interface{}: - val := make([]interface{}, len(res)) - for k, v := range res { - switch tng := v.(type) { - case *sql.Thing: - val[k], _ = e.fetchThing(ctx, tng, doc) - default: - val[k] = v - } - } - return val - case *sql.Thing: - val, _ = e.fetchThing(ctx, res, doc) - return val - } - } - return val - } - - res := doc.Fetch(fnc, val.VA).Data() - - return e.fetch(ctx, res, doc) - - } - - case *sql.Param: - - if len(val.VA) > 0 { - - for _, s := range paramSearchKeys { - - if obj, ok := ctx.Value(s).(*data.Doc); ok { - - fnc := func(key string, val interface{}, path []string) interface{} { - if len(path) > 0 { - switch res := val.(type) { - case []interface{}: - val := make([]interface{}, len(res)) - for k, v := range res { - switch tng := v.(type) { - case *sql.Thing: - val[k], _ = e.fetchThing(ctx, tng, doc) - default: - val[k] = v - } - } - return val - case *sql.Thing: - val, _ = e.fetchThing(ctx, res, doc) - return val - } - } - return val - } - - res := obj.Fetch(fnc, val.VA).Data() - - if res != nil { - return e.fetch(ctx, res, doc) - } - - } - - } - - } - - return nil, nil - - case *sql.RunStatement: - - return e.fetch(ctx, val.Expr, doc) - - case *sql.FuncExpression: - - var args []interface{} - for _, v := range val.Args { - val, err := e.fetch(ctx, v, doc) - if err != nil { - return nil, err - } - args = append(args, val) - } - res, err := fncs.Run(ctx, val.Name, args...) - if err != nil { - return nil, err - } - return e.fetch(ctx, res, doc) - - case *sql.SubExpression: - - switch exp := val.Expr.(type) { - default: - return e.fetch(ctx, exp, doc) - case *sql.IfelseStatement: - return e.fetchIfelse(ctx, exp, doc) - case *sql.SelectStatement: - return e.fetchSelect(ctx, exp, doc) - case *sql.CreateStatement: - return e.fetchCreate(ctx, exp, doc) - case *sql.UpdateStatement: - return e.fetchUpdate(ctx, exp, doc) - case *sql.DeleteStatement: - return e.fetchDelete(ctx, exp, doc) - case *sql.RelateStatement: - return e.fetchRelate(ctx, exp, doc) - case *sql.InsertStatement: - return e.fetchInsert(ctx, exp, doc) - case *sql.UpsertStatement: - return e.fetchUpsert(ctx, exp, doc) - } - - case *sql.MultExpression: - - for _, exp := range val.Expr { - - switch exp := exp.(type) { - default: - out, err = e.fetch(ctx, exp, doc) - case *sql.SelectStatement: - out, err = e.fetchSelect(ctx, exp, doc) - case *sql.CreateStatement: - out, err = e.fetchCreate(ctx, exp, doc) - case *sql.UpdateStatement: - out, err = e.fetchUpdate(ctx, exp, doc) - case *sql.DeleteStatement: - out, err = e.fetchDelete(ctx, exp, doc) - case *sql.RelateStatement: - out, err = e.fetchRelate(ctx, exp, doc) - case *sql.InsertStatement: - out, err = e.fetchInsert(ctx, exp, doc) - case *sql.UpsertStatement: - out, err = e.fetchUpsert(ctx, exp, doc) - } - - if err != nil { - return out, err - } - - } - - return nil, nil - - case *sql.PathExpression: - - return e.fetchPaths(ctx, doc, val.Expr...) - - case *sql.BinaryExpression: - - l, err := e.fetch(ctx, val.LHS, doc) - if err != nil { - return nil, err - } - - switch val.Op { - case sql.OR: - if calcAsBool(l) { - return true, nil - } - case sql.AND: - if !calcAsBool(l) { - return false, nil - } - } - - r, err := e.fetch(ctx, val.RHS, doc) - if err != nil { - return nil, err - } - - switch val.Op { - case sql.EEQ: - return l == r, nil - case sql.NEE: - return l != r, nil - case sql.AND, sql.OR: - return binaryBool(val.Op, l, r), nil - case sql.ADD, sql.SUB, sql.MUL, sql.DIV, sql.INC, sql.DEC: - return binaryMath(val.Op, l, r), nil - case sql.EQ, sql.NEQ, sql.ANY, sql.LT, sql.LTE, sql.GT, sql.GTE: - return binaryCheck(val.Op, l, r, val.LHS, val.RHS, doc), nil - case sql.SIN, sql.SNI, sql.INS, sql.NIS, sql.MAT, sql.NAT, sql.MAY: - return binaryCheck(val.Op, l, r, val.LHS, val.RHS, doc), nil - case sql.CONTAINSALL, sql.CONTAINSSOME, sql.CONTAINSNONE: - return binaryCheck(val.Op, l, r, val.LHS, val.RHS, doc), nil - case sql.ALLCONTAINEDIN, sql.SOMECONTAINEDIN, sql.NONECONTAINEDIN: - return binaryCheck(val.Op, l, r, val.LHS, val.RHS, doc), nil - } - - } - - return nil, nil - -} - -func (e *executor) fetchPaths(ctx context.Context, doc *data.Doc, exprs ...sql.Expr) (interface{}, error) { - - var expr sql.Expr - - if len(exprs) == 0 { - return doc.Data(), nil - } - - expr, exprs = exprs[0], exprs[1:] - - switch val := expr.(type) { - case *sql.JoinExpression: - switch val.Join { - case sql.DOT: - return e.fetchPaths(ctx, doc, exprs...) - case sql.OEDGE: - return nil, errFeatureNotImplemented - case sql.IEDGE: - return nil, errFeatureNotImplemented - case sql.BEDGE: - return nil, errFeatureNotImplemented - } - case *sql.PartExpression: - switch val := val.Part.(type) { - case *sql.All: - return e.fetchPaths(ctx, doc, exprs...) - case *sql.Param: - res, err := e.fetch(ctx, val, doc) - if err != nil { - return nil, err - } - return e.fetchPaths(ctx, data.Consume(res), exprs...) - case *sql.Ident: - res, err := e.fetch(ctx, val, doc) - if err != nil { - return nil, err - } - return e.fetchPaths(ctx, data.Consume(res), exprs...) - case *sql.Thing: - res, err := e.fetchThing(ctx, val, doc) - if err != nil { - return nil, err - } - return e.fetchPaths(ctx, data.Consume(res), exprs...) - } - } - - return nil, nil - -} - -func (e *executor) fetchThing(ctx context.Context, val *sql.Thing, doc *data.Doc) (interface{}, error) { - - ver, err := e.fetchVersion(ctx, ctx.Value(ctxKeyVersion)) - if err != nil { - return nil, err - } - - if val, ok := e.data.Load(val.String()); ok { - return val, nil - } - - stm := &sql.SelectStatement{ - Expr: []*sql.Field{{Expr: &sql.All{}}}, - What: []sql.Expr{val}, - Version: sql.Expr(ver), - } - - res, err := e.executeSelect(ctx, stm) - if err != nil { - return nil, err - } - - if len(res) > 0 { - e.data.Store(val.String(), res[0]) - return res[0], nil - } - - return nil, nil - -} - -func (e *executor) fetchPerms(ctx context.Context, val sql.Expr, tb *sql.Ident) error { - - // If the table does exist we reset the - // context to DB level so that no other - // embedded permissions are checked on - // records within these permissions. - - ctx = context.WithValue(ctx, ctxKeyKind, cnf.AuthDB) - - // We then try to process the relevant - // permissions expression, but only if - // the specified expression doesn't - // reference any document fields. - - res, err := e.fetch(ctx, val, ign) - - // If we receive an 'ident failed' error - // it is because the table permission - // expression contains a field check, - // and therefore we must check each - // record individually to see if it can - // be accessed or not. - - if err != queryIdentFailed { - if res, ok := res.(bool); ok && !res { - return &PermsError{table: tb.VA} - } - } - - return nil - -} - -func (e *executor) fetchLimit(ctx context.Context, val sql.Expr) (int, error) { - - v, err := e.fetch(ctx, val, nil) - if err != nil { - return -1, err - } - - switch v := v.(type) { - case float64: - return int(v), nil - case int64: - return int(v), nil - case nil: - return -1, nil - default: - return -1, &LimitError{found: v} - } - -} - -func (e *executor) fetchStart(ctx context.Context, val sql.Expr) (int, error) { - - v, err := e.fetch(ctx, val, nil) - if err != nil { - return -1, err - } - - switch v := v.(type) { - case float64: - return int(v), nil - case int64: - return int(v), nil - case nil: - return -1, nil - default: - return -1, &StartError{found: v} - } - -} - -func (e *executor) fetchVersion(ctx context.Context, val sql.Expr) (int64, error) { - - if v, ok := val.(int64); ok { - return v, nil - } - - v, err := e.fetch(ctx, val, nil) - if err != nil { - return math.MaxInt64, err - } - - switch v := v.(type) { - case time.Time: - return v.UnixNano(), nil - case nil: - return math.MaxInt64, nil - default: - return math.MaxInt64, &VersnError{found: v} - } - -} - -func (e *executor) fetchOutputs(ctx context.Context, stm *sql.SelectStatement) (int, error) { - - l, err := e.fetchLimit(ctx, stm.Limit) - if err != nil { - return -1, err - } - - if len(stm.What) == 1 { - if _, ok := stm.What[0].(*sql.Thing); ok { - l = 1 - } - } - - return l, nil - -} - -func calcAsBool(i interface{}) bool { - - switch v := i.(type) { - default: - return false - case bool: - return v - case int64: - return v > 0 - case float64: - return v > 0 - case string: - return v != "" - case time.Time: - return v.UnixNano() > 0 - case *sql.Thing: - return true - case []interface{}: - return len(v) > 0 - case map[string]interface{}: - return len(v) > 0 - } - -} - -func calcAsMath(i interface{}) float64 { - - switch v := i.(type) { - default: - return 0 - case bool: - if v { - return 1 - } - return 0 - case int64: - return float64(v) - case float64: - return v - case time.Time: - return float64(v.UnixNano()) - } - -} - -func binaryBool(op sql.Token, l, r interface{}) interface{} { - - switch op { - case sql.AND: - if calcAsBool(l) && calcAsBool(r) { - return l - } else { - return r - } - case sql.OR: - if calcAsBool(l) { - return l - } else { - return r - } - } - - return nil - -} - -func binaryMath(op sql.Token, l, r interface{}) interface{} { - - a := calcAsMath(l) - b := calcAsMath(r) - - switch op { - case sql.ADD, sql.INC: - return a + b - case sql.SUB, sql.DEC: - return a - b - case sql.MUL: - return a * b - case sql.DIV: - if b != 0 { - return a / b - } - } - - return nil - -} - -func binaryCheck(op sql.Token, l, r, lo, ro interface{}, d *data.Doc) interface{} { - - switch lo.(type) { - case *sql.Void: - switch ro.(type) { - case *sql.Null: - return op == sql.NEQ - case *sql.Void: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - } - case *sql.Empty: - switch ro.(type) { - case *sql.Null: - return op == sql.EQ - case *sql.Void: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - } - } - - switch ro.(type) { - case *sql.Void: - switch lo.(type) { - case *sql.Null: - return op == sql.NEQ - case *sql.Void: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - } - case *sql.Empty: - switch lo.(type) { - case *sql.Null: - return op == sql.EQ - case *sql.Void: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - } - } - - if d != nil { - - switch lo.(type) { - case *sql.Void: - switch r := ro.(type) { - case *sql.Ident: - if op == sql.EQ { - return d.Exists(r.VA) == false - } else if op == sql.NEQ { - return d.Exists(r.VA) == true - } - } - case *sql.Null: - switch r := ro.(type) { - case *sql.Ident: - if op == sql.EQ { - return d.Exists(r.VA) == true && d.Get(r.VA).Data() == nil - } else if op == sql.NEQ { - return d.Exists(r.VA) == false || d.Get(r.VA).Data() != nil - } - } - } - - switch ro.(type) { - case *sql.Void: - switch l := lo.(type) { - case *sql.Ident: - if op == sql.EQ { - return d.Exists(l.VA) == false - } else if op == sql.NEQ { - return d.Exists(l.VA) == true - } - } - case *sql.Null: - switch l := lo.(type) { - case *sql.Ident: - if op == sql.EQ { - return d.Exists(l.VA) == true && d.Get(l.VA).Data() == nil - } else if op == sql.NEQ { - return d.Exists(l.VA) == false || d.Get(l.VA).Data() != nil - } - } - } - - } - - switch l := l.(type) { - - case nil: - switch r := r.(type) { - case nil: - return op == sql.EQ - case *sql.Null: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - case []interface{}: - return chkArrayR(op, l, r) - } - - case *sql.Null: - switch r := r.(type) { - case nil: - return op == sql.EQ - case *sql.Null: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - case []interface{}: - return chkArrayR(op, l, r) - } - - case *sql.Empty: - switch r := r.(type) { - case nil: - return op == sql.EQ - case *sql.Null: - return op == sql.EQ - case *sql.Empty: - return op == sql.EQ - case string: - return chkLen(op, r) - case []interface{}: - return chkArrayR(op, l, r) - case map[string]interface{}: - return chkObject(op, r, l) - } - - case *sql.Thing: - switch r := r.(type) { - case *sql.Thing: - return chkThing(op, l, r) - case string: - return chkString(op, r, l.String()) - case []interface{}: - return chkArrayR(op, l, r) - } - - case *sql.Point: - switch r := r.(type) { - case *sql.Point: - return chkPoint(op, l, r) - case *sql.Polygon: - switch op { - case sql.INS: - return geof.Inside(l, r) == true - case sql.NIS: - return geof.Inside(l, r) == false - } - } - - case *sql.Polygon: - switch r := r.(type) { - case *sql.Point: - switch op { - case sql.SIN: - return geof.Contains(l, r) == true - case sql.SNI: - return geof.Contains(l, r) == false - } - case []interface{}: - if p, ok := geof.Point(r); ok { - switch op { - case sql.SIN: - return geof.Contains(l, p) == true - case sql.SNI: - return geof.Contains(l, p) == false - } - } else { - return chkPolygonL(op, l, r) - } - } - - case bool: - switch r := r.(type) { - case bool: - return chkBool(op, l, r) - case string: - if b, err := strconv.ParseBool(r); err == nil { - return chkBool(op, l, b) - } - case *regexp.Regexp: - return chkRegex(op, strconv.FormatBool(l), r) - case []interface{}: - return chkArrayR(op, l, r) - } - - case string: - switch r := r.(type) { - case bool: - if b, err := strconv.ParseBool(l); err == nil { - return chkBool(op, r, b) - } - case string: - return chkString(op, l, r) - case int64: - if n, err := strconv.ParseInt(l, 10, 64); err == nil { - return chkInt(op, r, n) - } - case float64: - if n, err := strconv.ParseFloat(l, 64); err == nil { - return chkFloat(op, r, n) - } - case time.Time: - return chkString(op, l, r.String()) - case *sql.Empty: - return chkLen(op, l) - case *sql.Thing: - return chkString(op, l, r.String()) - case *regexp.Regexp: - return chkRegex(op, l, r) - case []interface{}: - return chkArrayR(op, l, r) - } - - case int64: - switch r := r.(type) { - case string: - if n, err := strconv.ParseInt(r, 10, 64); err == nil { - return chkInt(op, l, n) - } - case int64: - return chkInt(op, l, r) - case float64: - return chkFloat(op, float64(l), r) - case time.Time: - return chkInt(op, l, r.UnixNano()) - case *regexp.Regexp: - return chkRegex(op, strconv.FormatInt(l, 10), r) - case []interface{}: - return chkArrayR(op, l, r) - } - - case float64: - switch r := r.(type) { - case string: - if n, err := strconv.ParseFloat(r, 64); err == nil { - return chkFloat(op, l, n) - } - case int64: - return chkFloat(op, l, float64(r)) - case float64: - return chkFloat(op, l, r) - case time.Time: - return chkFloat(op, l, float64(r.UnixNano())) - case *regexp.Regexp: - return chkRegex(op, strconv.FormatFloat(l, 'g', -1, 64), r) - case []interface{}: - return chkArrayR(op, l, r) - } - - case time.Time: - switch r := r.(type) { - case string: - return chkString(op, l.String(), r) - case int64: - return chkInt(op, l.UnixNano(), r) - case float64: - return chkFloat(op, float64(l.UnixNano()), r) - case time.Time: - return chkInt(op, l.UnixNano(), r.UnixNano()) - case *regexp.Regexp: - return chkRegex(op, l.String(), r) - case []interface{}: - return chkArrayR(op, l, r) - } - - case []interface{}: - switch r := r.(type) { - default: - return chkArrayL(op, l, r) - case bool: - return chkArrayL(op, l, r) - case string: - return chkArrayL(op, l, r) - case int64: - return chkArrayL(op, l, r) - case float64: - return chkArrayL(op, l, r) - case time.Time: - return chkArrayL(op, l, r) - case *regexp.Regexp: - return chkMatch(op, l, r) - case []interface{}: - return chkArray(op, l, r) - case map[string]interface{}: - return chkArrayL(op, l, r) - case *sql.Polygon: - return chkPolygonR(op, l, r) - } - - case map[string]interface{}: - switch r := r.(type) { - default: - return chkObject(op, l, r) - case []interface{}: - return chkArrayR(op, l, r) - case map[string]interface{}: - return chkObject(op, l, r) - } - - } - - return negOp(op) - -} - -func posOp(op sql.Token) bool { - return chkOp(op) > 1 -} - -func negOp(op sql.Token) bool { - return chkOp(op) < 0 -} - -func chkOp(op sql.Token) int8 { - switch op { - case sql.EQ, sql.SIN, sql.INS, sql.MAT, sql.ANY: - return +1 - case sql.NEQ, sql.SNI, sql.NIS, sql.NAT, sql.MAY: - return -1 - case sql.CONTAINSALL: - return +1 - case sql.CONTAINSSOME: - return +1 - case sql.CONTAINSNONE: - return -1 - case sql.ALLCONTAINEDIN: - return +1 - case sql.SOMECONTAINEDIN: - return +1 - case sql.NONECONTAINEDIN: - return -1 - default: - return 0 - } -} - -func chkLen(op sql.Token, s string) (val bool) { - switch op { - case sql.EQ: - return len(s) == 0 - case sql.NEQ: - return len(s) != 0 - } - return negOp(op) -} - -func chkBool(op sql.Token, a, b bool) (val bool) { - switch op { - case sql.EQ: - return a == b - case sql.NEQ: - return a != b - } - return negOp(op) -} - -func chkString(op sql.Token, a, b string) (val bool) { - switch op { - case sql.EQ: - return a == b - case sql.NEQ: - return a != b - case sql.LT: - return a < b - case sql.LTE: - return a <= b - case sql.GT: - return a > b - case sql.GTE: - return a >= b - case sql.INS: - return strings.Contains(b, a) == true - case sql.NIS: - return strings.Contains(b, a) == false - case sql.SIN: - return strings.Contains(a, b) == true - case sql.SNI: - return strings.Contains(a, b) == false - case sql.MAT: - b, e := search.New(language.Und, search.Loose).IndexString(a, b) - return b != -1 && e != -1 - case sql.NAT: - b, e := search.New(language.Und, search.Loose).IndexString(a, b) - return b == -1 && e == -1 - case sql.MAY: - b, e := search.New(language.Und, search.Loose).IndexString(a, b) - return b != -1 && e != -1 - } - return negOp(op) -} - -func chkInt(op sql.Token, a, b int64) (val bool) { - switch op { - case sql.EQ: - return a == b - case sql.NEQ: - return a != b - case sql.LT: - return a < b - case sql.LTE: - return a <= b - case sql.GT: - return a > b - case sql.GTE: - return a >= b - } - return negOp(op) -} - -func chkFloat(op sql.Token, a, b float64) (val bool) { - switch op { - case sql.EQ: - return a == b - case sql.NEQ: - return a != b - case sql.LT: - return a < b - case sql.LTE: - return a <= b - case sql.GT: - return a > b - case sql.GTE: - return a >= b - } - return negOp(op) -} - -func chkThing(op sql.Token, a, b *sql.Thing) (val bool) { - switch op { - case sql.EQ: - return a.TB == b.TB && a.ID == b.ID - case sql.NEQ: - return a.TB != b.TB || a.ID != b.ID - } - return negOp(op) -} - -func chkPoint(op sql.Token, a, b *sql.Point) (val bool) { - switch op { - case sql.EQ: - return a.LA == b.LA && a.LO == b.LO - case sql.NEQ: - return a.LA != b.LA || a.LO != b.LO - } - return negOp(op) -} - -func chkRegex(op sql.Token, a string, r *regexp.Regexp) (val bool) { - switch op { - case sql.EQ: - return r.MatchString(a) == true - case sql.NEQ: - return r.MatchString(a) == false - case sql.ANY: - return r.MatchString(a) == true - } - return negOp(op) -} - -func chkObject(op sql.Token, m map[string]interface{}, i interface{}) (val bool) { - switch op { - case sql.EQ: - switch i.(type) { - case *sql.Empty: - return len(m) == 0 - default: - return reflect.TypeOf(m) == reflect.TypeOf(i) && reflect.DeepEqual(m, i) == true - } - case sql.NEQ: - switch i.(type) { - case *sql.Empty: - return len(m) != 0 - default: - return reflect.TypeOf(m) != reflect.TypeOf(i) || reflect.DeepEqual(m, i) == false - } - } - return negOp(op) -} - -func chkPolygonL(op sql.Token, a *sql.Polygon, b []interface{}) (val bool) { - switch op { - case sql.CONTAINSALL: - for _, v := range b { - if p, ok := geof.Point(v); ok { - if geof.Contains(a, p) == false { - return false - } - } - } - return true - case sql.CONTAINSSOME: - for _, v := range b { - if p, ok := geof.Point(v); ok { - if geof.Contains(a, p) == true { - return true - } - } - } - return false - case sql.CONTAINSNONE: - for _, v := range b { - if p, ok := geof.Point(v); ok { - if geof.Contains(a, p) == true { - return false - } - } - } - return true - } - return -} - -func chkPolygonR(op sql.Token, a []interface{}, b *sql.Polygon) (val bool) { - switch op { - case sql.ALLCONTAINEDIN: - for _, v := range a { - if p, ok := geof.Point(v); ok { - if geof.Contains(b, p) == false { - return false - } - } - } - return true - case sql.SOMECONTAINEDIN: - for _, v := range a { - if p, ok := geof.Point(v); ok { - if geof.Contains(b, p) == true { - return true - } - } - } - return false - case sql.NONECONTAINEDIN: - for _, v := range a { - if p, ok := geof.Point(v); ok { - if geof.Contains(b, p) == true { - return false - } - } - } - return true - } - return -} - -func chkArrayL(op sql.Token, a []interface{}, i interface{}) (val bool) { - switch op { - case sql.EQ: - switch i.(type) { - case *sql.Empty: - return len(a) == 0 - default: - return false - } - case sql.NEQ: - switch i.(type) { - case *sql.Empty: - return len(a) != 0 - default: - return true - } - case sql.SIN: - switch i.(type) { - case nil, *sql.Null: - return data.Consume(a).Contains(nil) == true - default: - return data.Consume(a).Contains(i) == true - } - case sql.SNI: - switch i.(type) { - case nil, *sql.Null: - return data.Consume(a).Contains(nil) == false - default: - return data.Consume(a).Contains(i) == false - } - case sql.MAT: - switch s := i.(type) { - case string: - return chkSearchL(op, a, s) - } - case sql.NAT: - switch s := i.(type) { - case string: - return chkSearchL(op, a, s) - } - case sql.MAY: - switch s := i.(type) { - case string: - return chkSearchL(op, a, s) - } - } - return negOp(op) -} - -func chkArrayR(op sql.Token, i interface{}, a []interface{}) (val bool) { - switch op { - case sql.EQ: - switch i.(type) { - case *sql.Empty: - return len(a) == 0 - default: - return false - } - case sql.NEQ: - switch i.(type) { - case *sql.Empty: - return len(a) != 0 - default: - return true - } - case sql.INS: - switch i.(type) { - case nil, *sql.Null: - return data.Consume(a).Contains(nil) == true - default: - return data.Consume(a).Contains(i) == true - } - case sql.NIS: - switch i.(type) { - case nil, *sql.Null: - return data.Consume(a).Contains(nil) == false - default: - return data.Consume(a).Contains(i) == false - } - case sql.MAT: - switch s := i.(type) { - case string: - return chkSearchR(op, a, s) - } - case sql.NAT: - switch s := i.(type) { - case string: - return chkSearchR(op, a, s) - } - case sql.MAY: - switch s := i.(type) { - case string: - return chkSearchR(op, a, s) - } - } - return negOp(op) -} - -func chkArray(op sql.Token, a []interface{}, b []interface{}) (val bool) { - switch op { - case sql.EQ: - if reflect.TypeOf(a) == reflect.TypeOf(b) && reflect.DeepEqual(a, b) == true { - return true - } - case sql.NEQ: - if reflect.TypeOf(a) != reflect.TypeOf(b) || reflect.DeepEqual(a, b) == false { - return true - } - case sql.SIN: - return data.Consume(a).Contains(b) == true - case sql.SNI: - return data.Consume(a).Contains(b) == false - case sql.INS: - return data.Consume(b).Contains(a) == true - case sql.NIS: - return data.Consume(b).Contains(a) == false - case sql.CONTAINSALL: - for _, v := range b { - if data.Consume(a).Contains(v) == false { - return false - } - } - return true - case sql.CONTAINSSOME: - for _, v := range b { - if data.Consume(a).Contains(v) == true { - return true - } - } - return false - case sql.CONTAINSNONE: - for _, v := range b { - if data.Consume(a).Contains(v) == true { - return false - } - } - return true - case sql.ALLCONTAINEDIN: - for _, v := range a { - if data.Consume(b).Contains(v) == false { - return false - } - } - return true - case sql.SOMECONTAINEDIN: - for _, v := range a { - if data.Consume(b).Contains(v) == true { - return true - } - } - return false - case sql.NONECONTAINEDIN: - for _, v := range a { - if data.Consume(b).Contains(v) == true { - return false - } - } - return true - } - return -} - -func chkMatch(op sql.Token, a []interface{}, r *regexp.Regexp) (val bool) { - - if len(a) == 0 { - return op == sql.NEQ - } - - for _, v := range a { - - var s string - - switch c := v.(type) { - default: - return false - case string: - s = c - case bool: - s = strconv.FormatBool(c) - case int64: - s = strconv.FormatInt(c, 10) - case float64: - s = strconv.FormatFloat(c, 'g', -1, 64) - case time.Time: - s = c.String() - } - - if op == sql.EQ { - if chkRegex(sql.EQ, s, r) == false { - return false - } - } - - if op == sql.NEQ { - if chkRegex(sql.EQ, s, r) == false { - return true - } - } - - if op == sql.ANY { - if chkRegex(sql.EQ, s, r) == true { - return true - } - } - - } - - switch op { - case sql.EQ: - return true - case sql.NEQ: - return false - case sql.ANY: - return false - } - - return - -} - -func chkSearchL(op sql.Token, a []interface{}, p string) (val bool) { - - if len(a) == 0 { - return op == sql.NAT - } - - for _, v := range a { - - var s string - - switch c := v.(type) { - default: - return false - case string: - s = c - case bool: - s = strconv.FormatBool(c) - case int64: - s = strconv.FormatInt(c, 10) - case float64: - s = strconv.FormatFloat(c, 'g', -1, 64) - case time.Time: - s = c.String() - } - - if op == sql.MAT { - b, e := search.New(language.Und, search.Loose).IndexString(s, p) - if b == -1 && e == -1 { - return false - } - } - - if op == sql.NAT { - b, e := search.New(language.Und, search.Loose).IndexString(s, p) - if b == -1 && e == -1 { - return true - } - } - - if op == sql.MAY { - b, e := search.New(language.Und, search.Loose).IndexString(s, p) - if b != -1 && e != -1 { - return true - } - } - - } - - switch op { - case sql.MAT: - return true - case sql.NAT: - return false - case sql.MAY: - return false - } - - return - -} - -func chkSearchR(op sql.Token, a []interface{}, p string) (val bool) { - - if len(a) == 0 { - return op == sql.NAT - } - - for _, v := range a { - - var s string - - switch c := v.(type) { - default: - return false - case string: - s = c - case bool: - s = strconv.FormatBool(c) - case int64: - s = strconv.FormatInt(c, 10) - case float64: - s = strconv.FormatFloat(c, 'g', -1, 64) - case time.Time: - s = c.String() - } - - if op == sql.MAT { - b, e := search.New(language.Und, search.Loose).IndexString(p, s) - if b == -1 && e == -1 { - return false - } - } - - if op == sql.NAT { - b, e := search.New(language.Und, search.Loose).IndexString(p, s) - if b == -1 && e == -1 { - return true - } - } - - if op == sql.MAY { - b, e := search.New(language.Und, search.Loose).IndexString(p, s) - if b != -1 && e != -1 { - return true - } - } - - } - - switch op { - case sql.MAT: - return true - case sql.NAT: - return false - case sql.MAY: - return false - } - - return - -} diff --git a/db/fetch_test.go b/db/fetch_test.go deleted file mode 100644 index 42d78ed9..00000000 --- a/db/fetch_test.go +++ /dev/null @@ -1,1037 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func inc(val *int) int { - *val++ - return *val -} - -func TestFetch(t *testing.T) { - - Convey("Check calc-as-bool expressions", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - SELECT * FROM "test" WHERE gone; - SELECT * FROM "test" WHERE true; - SELECT * FROM "test" WHERE 0; - SELECT * FROM "test" WHERE -1; - SELECT * FROM "test" WHERE +1; - SELECT * FROM "test" WHERE "test"; - SELECT * FROM "test" WHERE time.now(); - - SELECT * FROM "test" WHERE []; - SELECT * FROM "test" WHERE [1,2,3]; - - SELECT * FROM "test" WHERE {}; - SELECT * FROM "test" WHERE {test:true}; - - SELECT * FROM "test" WHERE gone OR gone; - SELECT * FROM "test" WHERE true OR true; - SELECT * FROM "test" WHERE gone OR true; - - SELECT * FROM "test" WHERE gone AND gone; - SELECT * FROM "test" WHERE true AND true; - SELECT * FROM "test" WHERE gone AND true; - - ` - - i := 0 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 18) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - }) - - Convey("Check calc-as-math expressions", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - SELECT * FROM "test" WHERE 0 + false; - SELECT * FROM "test" WHERE 1 + false; - - SELECT * FROM "test" WHERE 0 + true; - SELECT * FROM "test" WHERE 1 + true; - - SELECT * FROM "test" WHERE time.now() + 1; - - SELECT * FROM "test" WHERE [] + []; - SELECT * FROM "test" WHERE {} + {}; - - ` - - i := 0 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - }) - - Convey("Check binary math comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - SELECT * FROM "test" WHERE 1 = 1; - SELECT * FROM "test" WHERE 1 != 1; - - SELECT * FROM "test" WHERE 1 < 2; - SELECT * FROM "test" WHERE 1 > 2; - SELECT * FROM "test" WHERE 1 <= 2; - SELECT * FROM "test" WHERE 1 >= 2; - - SELECT * FROM "test" WHERE 10-10 = 0; - SELECT * FROM "test" WHERE 10+10 = 20; - SELECT * FROM "test" WHERE 10*10 = 100; - SELECT * FROM "test" WHERE 10/10 = 1; - - ` - - i := 0 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary NULL comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - LET var = NULL; - - SELECT * FROM "test" WHERE NULL = ""; - SELECT * FROM "test" WHERE NULL = []; - SELECT * FROM "test" WHERE NULL = {}; - SELECT * FROM "test" WHERE NULL = $var; - SELECT * FROM "test" WHERE NULL = VOID; - SELECT * FROM "test" WHERE NULL = NULL; - SELECT * FROM "test" WHERE NULL = EMPTY; - SELECT * FROM "test" WHERE NULL = something; - SELECT * FROM { test: [] } WHERE NULL = test; - SELECT * FROM { test: {} } WHERE NULL = test; - - SELECT * FROM "test" WHERE "" = NULL; - SELECT * FROM "test" WHERE [] = NULL; - SELECT * FROM "test" WHERE {} = NULL; - SELECT * FROM "test" WHERE $var = NULL; - SELECT * FROM "test" WHERE VOID = NULL; - SELECT * FROM "test" WHERE NULL = NULL; - SELECT * FROM "test" WHERE EMPTY = NULL; - SELECT * FROM "test" WHERE something = NULL; - SELECT * FROM { test: [] } WHERE test = NULL; - SELECT * FROM { test: {} } WHERE test = NULL; - - SELECT * FROM "test" WHERE NULL != ""; - SELECT * FROM "test" WHERE NULL != []; - SELECT * FROM "test" WHERE NULL != {}; - SELECT * FROM "test" WHERE NULL != $var; - SELECT * FROM "test" WHERE NULL != VOID; - SELECT * FROM "test" WHERE NULL != NULL; - SELECT * FROM "test" WHERE NULL != EMPTY; - SELECT * FROM "test" WHERE NULL != something; - SELECT * FROM { test: [] } WHERE NULL != test; - SELECT * FROM { test: {} } WHERE NULL != test; - - SELECT * FROM "test" WHERE "" != NULL; - SELECT * FROM "test" WHERE [] != NULL; - SELECT * FROM "test" WHERE {} != NULL; - SELECT * FROM "test" WHERE $var != NULL; - SELECT * FROM "test" WHERE VOID != NULL; - SELECT * FROM "test" WHERE NULL != NULL; - SELECT * FROM "test" WHERE EMPTY != NULL; - SELECT * FROM "test" WHERE something != NULL; - SELECT * FROM { test: [] } WHERE test != NULL; - SELECT * FROM { test: {} } WHERE test != NULL; - - SELECT * FROM "test" WHERE NULL ∈ []; - SELECT * FROM "test" WHERE NULL ∉ []; - SELECT * FROM "test" WHERE NULL ∋ []; - SELECT * FROM "test" WHERE NULL ∌ []; - - SELECT * FROM "test" WHERE [] ∈ NULL; - SELECT * FROM "test" WHERE [] ∉ NULL; - SELECT * FROM "test" WHERE [] ∋ NULL; - SELECT * FROM "test" WHERE [] ∌ NULL; - - SELECT * FROM "test" WHERE NULL ∈ [null]; - SELECT * FROM "test" WHERE NULL ∉ [null]; - SELECT * FROM "test" WHERE [null] ∋ NULL; - SELECT * FROM "test" WHERE [null] ∌ NULL; - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 54) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - }) - - Convey("Check binary VOID comparisons", t, func() { - - txt := ` - - USE NS test DB test; - - LET var = NULL; - - SELECT * FROM "test" WHERE VOID = ""; - SELECT * FROM "test" WHERE VOID = []; - SELECT * FROM "test" WHERE VOID = {}; - SELECT * FROM "test" WHERE VOID = $var; - SELECT * FROM "test" WHERE VOID = NULL; - SELECT * FROM "test" WHERE VOID = VOID; - SELECT * FROM "test" WHERE VOID = EMPTY; - SELECT * FROM "test" WHERE VOID = something; - SELECT * FROM { test: [] } WHERE VOID = test; - SELECT * FROM { test: {} } WHERE VOID = test; - - SELECT * FROM "test" WHERE "" = VOID; - SELECT * FROM "test" WHERE [] = VOID; - SELECT * FROM "test" WHERE {} = VOID; - SELECT * FROM "test" WHERE $var = VOID; - SELECT * FROM "test" WHERE NULL = VOID; - SELECT * FROM "test" WHERE VOID = VOID; - SELECT * FROM "test" WHERE EMPTY = VOID; - SELECT * FROM "test" WHERE something = VOID; - SELECT * FROM { test: [] } WHERE test = VOID; - SELECT * FROM { test: {} } WHERE test = VOID; - - SELECT * FROM "test" WHERE VOID != ""; - SELECT * FROM "test" WHERE VOID != []; - SELECT * FROM "test" WHERE VOID != {}; - SELECT * FROM "test" WHERE VOID != $var; - SELECT * FROM "test" WHERE VOID != NULL; - SELECT * FROM "test" WHERE VOID != VOID; - SELECT * FROM "test" WHERE VOID != EMPTY; - SELECT * FROM "test" WHERE VOID != something; - SELECT * FROM { test: [] } WHERE VOID != test; - SELECT * FROM { test: {} } WHERE VOID != test; - - SELECT * FROM "test" WHERE "" != VOID; - SELECT * FROM "test" WHERE [] != VOID; - SELECT * FROM "test" WHERE {} != VOID; - SELECT * FROM "test" WHERE $var != VOID; - SELECT * FROM "test" WHERE NULL != VOID; - SELECT * FROM "test" WHERE VOID != VOID; - SELECT * FROM "test" WHERE EMPTY != VOID; - SELECT * FROM "test" WHERE something != VOID; - SELECT * FROM { test: [] } WHERE test != VOID; - SELECT * FROM { test: {} } WHERE test != VOID; - - SELECT * FROM "test" WHERE VOID ∈ []; - SELECT * FROM "test" WHERE VOID ∉ []; - SELECT * FROM "test" WHERE VOID ∋ []; - SELECT * FROM "test" WHERE VOID ∌ []; - - SELECT * FROM "test" WHERE [] ∈ VOID; - SELECT * FROM "test" WHERE [] ∉ VOID; - SELECT * FROM "test" WHERE [] ∋ VOID; - SELECT * FROM "test" WHERE [] ∌ VOID; - - SELECT * FROM "test" WHERE VOID ∈ [null]; - SELECT * FROM "test" WHERE VOID ∉ [null]; - SELECT * FROM "test" WHERE [null] ∋ VOID; - SELECT * FROM "test" WHERE [null] ∌ VOID; - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 54) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary EMPTY comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - LET var = NULL; - - SELECT * FROM "test" WHERE EMPTY = ""; - SELECT * FROM "test" WHERE EMPTY = []; - SELECT * FROM "test" WHERE EMPTY = {}; - SELECT * FROM "test" WHERE EMPTY = $var; - SELECT * FROM "test" WHERE EMPTY = NULL; - SELECT * FROM "test" WHERE EMPTY = VOID; - SELECT * FROM "test" WHERE EMPTY = EMPTY; - SELECT * FROM "test" WHERE EMPTY = something; - SELECT * FROM { test: [] } WHERE EMPTY = test; - SELECT * FROM { test: {} } WHERE EMPTY = test; - - SELECT * FROM "test" WHERE "" = EMPTY; - SELECT * FROM "test" WHERE [] = EMPTY; - SELECT * FROM "test" WHERE {} = EMPTY; - SELECT * FROM "test" WHERE $var = EMPTY; - SELECT * FROM "test" WHERE NULL = EMPTY; - SELECT * FROM "test" WHERE VOID = EMPTY; - SELECT * FROM "test" WHERE EMPTY = EMPTY; - SELECT * FROM "test" WHERE something = EMPTY; - SELECT * FROM { test: [] } WHERE test = EMPTY; - SELECT * FROM { test: {} } WHERE test = EMPTY; - - SELECT * FROM "test" WHERE EMPTY != ""; - SELECT * FROM "test" WHERE EMPTY != []; - SELECT * FROM "test" WHERE EMPTY != {}; - SELECT * FROM "test" WHERE EMPTY != $var; - SELECT * FROM "test" WHERE EMPTY != NULL; - SELECT * FROM "test" WHERE EMPTY != VOID; - SELECT * FROM "test" WHERE EMPTY != EMPTY; - SELECT * FROM "test" WHERE EMPTY != something; - SELECT * FROM { test: [] } WHERE EMPTY != test; - SELECT * FROM { test: {} } WHERE EMPTY != test; - - SELECT * FROM "test" WHERE "" != EMPTY; - SELECT * FROM "test" WHERE [] != EMPTY; - SELECT * FROM "test" WHERE {} != EMPTY; - SELECT * FROM "test" WHERE $var != EMPTY; - SELECT * FROM "test" WHERE NULL != EMPTY; - SELECT * FROM "test" WHERE VOID != EMPTY; - SELECT * FROM "test" WHERE EMPTY != EMPTY; - SELECT * FROM "test" WHERE something != EMPTY; - SELECT * FROM { test: [] } WHERE test != EMPTY; - SELECT * FROM { test: {} } WHERE test != EMPTY; - - SELECT * FROM "test" WHERE EMPTY ∈ []; - SELECT * FROM "test" WHERE EMPTY ∉ []; - SELECT * FROM "test" WHERE EMPTY ∋ []; - SELECT * FROM "test" WHERE EMPTY ∌ []; - - SELECT * FROM "test" WHERE [] ∈ EMPTY; - SELECT * FROM "test" WHERE [] ∉ EMPTY; - SELECT * FROM "test" WHERE [] ∋ EMPTY; - SELECT * FROM "test" WHERE [] ∌ EMPTY; - - SELECT * FROM "test" WHERE EMPTY ∈ [null]; - SELECT * FROM "test" WHERE EMPTY ∉ [null]; - SELECT * FROM "test" WHERE [null] ∋ EMPTY; - SELECT * FROM "test" WHERE [null] ∌ EMPTY; - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 54) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary thing comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - -- ------------------------------ - - SELECT * FROM "test" WHERE person:test = person:test; - SELECT * FROM "test" WHERE person:test = "person:test"; - SELECT * FROM "test" WHERE person:test ∈ array(person:test); - - -- ------------------------------ - - SELECT * FROM "test" WHERE person:test = person:test; - SELECT * FROM "test" WHERE person:test != person:test; - SELECT * FROM "test" WHERE person:test = user:test; - SELECT * FROM "test" WHERE person:test != user:test; - - ` - - i := 0 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary bool comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - -- ------------------------------ - - SELECT * FROM "test" WHERE true = true; - SELECT * FROM "test" WHERE true = "true"; - SELECT * FROM "test" WHERE true = /\w/; - SELECT * FROM "test" WHERE true ∈ [true,false]; - - -- ------------------------------ - - SELECT * FROM "test" WHERE true = true; - SELECT * FROM "test" WHERE true != true; - SELECT * FROM "test" WHERE false = false; - SELECT * FROM "test" WHERE false != false; - - ` - - i := 0 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - }) - - Convey("Check binary float comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - LET timer = "1987-06-22T08:30:30.511Z"; - - -- ------------------------------ - - SELECT * FROM "test" WHERE 1 = "1"; - SELECT * FROM "test" WHERE 1 = /\d/; - SELECT * FROM "test" WHERE 1 ∈ [1,2,3]; - SELECT * FROM "test" WHERE 551349030511000000 = $timer; - - -- ------------------------------ - - SELECT * FROM "test" WHERE 1 = 1; - SELECT * FROM "test" WHERE 1.1 != 1.1; - - SELECT * FROM "test" WHERE 1 < 2; - SELECT * FROM "test" WHERE 1 > 2; - SELECT * FROM "test" WHERE 1 <= 2; - SELECT * FROM "test" WHERE 1 >= 2; - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 12) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - }) - - Convey("Check binary string comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - LET timer = "1987-06-22T08:30:30.511Z"; - - -- ------------------------------ - - SELECT * FROM "test" WHERE "true" = true; - SELECT * FROM "test" WHERE "1.1" = 1.1; - SELECT * FROM "test" WHERE "person:test" = person:test; - SELECT * FROM "test" WHERE "test" = /\w/; - SELECT * FROM "test" WHERE "test" ∈ ["test","some"]; - SELECT * FROM "test" WHERE "1987-06-22 08:30:30.511 +0000 UTC" = $timer; - - -- ------------------------------ - - SELECT * FROM "test" WHERE "test" = "test"; - SELECT * FROM "test" WHERE "test" != "test"; - - SELECT * FROM "test" WHERE "abc" < "def"; - SELECT * FROM "test" WHERE "abc" > "def"; - SELECT * FROM "test" WHERE "abc" <= "def"; - SELECT * FROM "test" WHERE "abc" >= "def"; - - SELECT * FROM "test" WHERE "a true test string" ∋ "test"; - SELECT * FROM "test" WHERE "a true test string" ∌ "test"; - SELECT * FROM "test" WHERE "test" ∈ "a true test string"; - SELECT * FROM "test" WHERE "test" ∉ "a true test string"; - - SELECT * FROM "test" WHERE "a true test string" ~ "test"; - SELECT * FROM "test" WHERE "a true test string" ~ "Test"; - SELECT * FROM "test" WHERE "a true test string" !~ "test"; - SELECT * FROM "test" WHERE "a true test string" !~ "Test"; - SELECT * FROM "test" WHERE "a true test string" ?~ "test"; - SELECT * FROM "test" WHERE "a true test string" ?~ "Test"; - - SELECT * FROM "test" WHERE "a true test string" = /test/; - SELECT * FROM "test" WHERE "a true test string" = /Test/; - SELECT * FROM "test" WHERE "a true test string" = /(?i)Test/; - SELECT * FROM "test" WHERE "a true test string" != /test/; - SELECT * FROM "test" WHERE "a true test string" != /Test/; - SELECT * FROM "test" WHERE "a true test string" != /(?i)Test/; - SELECT * FROM "test" WHERE "a true test string" ?= /test/; - SELECT * FROM "test" WHERE "a true test string" ?= /Test/; - SELECT * FROM "test" WHERE "a true test string" ?= /(?i)Test/; - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 33) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary time.Time comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - LET timer = "1987-06-22T08:30:30.511Z"; - - -- ------------------------------ - - SELECT * FROM "test" WHERE $timer = "1987-06-22 08:30:30.511 +0000 UTC"; - SELECT * FROM "test" WHERE $timer = 551349030511000000; - SELECT * FROM "test" WHERE $timer = $timer; - SELECT * FROM "test" WHERE $timer = /\d/; - SELECT * FROM "test" WHERE $timer ∈ array($timer); - - -- ------------------------------ - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary array comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - LET timer = "1987-06-22T08:30:30.511Z"; - - -- ------------------------------ - - SELECT * FROM "test" WHERE [true] ∋ true; - SELECT * FROM "test" WHERE ["test"] ∋ "test"; - SELECT * FROM "test" WHERE [1,2,3] ∋ 1; - SELECT * FROM "test" WHERE array($timer) ∋ $timer; - SELECT * FROM "test" WHERE [1,2,3] = /\d/; - SELECT * FROM "test" WHERE [{test:true}] ∋ {test:true}; - - -- ------------------------------ - - SELECT * FROM "test" WHERE [] = []; - SELECT * FROM "test" WHERE [] != []; - - SELECT * FROM "test" WHERE [1,2,3] = [1,2,3]; - SELECT * FROM "test" WHERE [1,2,3] = [4,5,6]; - SELECT * FROM "test" WHERE [1,2,3] != [1,2,3]; - SELECT * FROM "test" WHERE [1,2,3] != [4,5,6]; - - SELECT * FROM "test" WHERE [1,2,3] ∈ [ [1,2,3] ]; - SELECT * FROM "test" WHERE [1,2,3] ∉ [ [1,2,3] ]; - SELECT * FROM "test" WHERE [ [1,2,3] ] ∋ [1,2,3]; - SELECT * FROM "test" WHERE [ [1,2,3] ] ∌ [1,2,3]; - - SELECT * FROM "test" WHERE [1,2,3,4,5] ⊇ [1,2,3]; - SELECT * FROM "test" WHERE [1,2,3,4,5] ⊇ [2,4,6]; - SELECT * FROM "test" WHERE [1,3,5,7,9] ⊃ [1,2,3]; - SELECT * FROM "test" WHERE [1,3,5,7,9] ⊃ [2,4,6]; - SELECT * FROM "test" WHERE [1,3,5,7,9] ⊅ [1,2,3]; - SELECT * FROM "test" WHERE [1,3,5,7,9] ⊅ [2,4,6]; - - SELECT * FROM "test" WHERE [1,2,3] ⊆ [1,2,3,4,5]; - SELECT * FROM "test" WHERE [2,4,6] ⊆ [1,2,3,4,5]; - SELECT * FROM "test" WHERE [1,2,3] ⊂ [1,3,5,7,9]; - SELECT * FROM "test" WHERE [2,4,6] ⊂ [1,3,5,7,9]; - SELECT * FROM "test" WHERE [1,2,3] ⊄ [1,3,5,7,9]; - SELECT * FROM "test" WHERE [2,4,6] ⊄ [1,3,5,7,9]; - - SELECT * FROM "test" WHERE [] = /[0-9]/; - SELECT * FROM "test" WHERE [1,2,3] = /[0-9]/; - SELECT * FROM "test" WHERE [1,"2",true] = /[0-9]/; - SELECT * FROM "test" WHERE ["a","b","c"] = /[0-9]/; - - SELECT * FROM "test" WHERE [] != /[0-9]/; - SELECT * FROM "test" WHERE [1,2,3] != /[0-9]/; - SELECT * FROM "test" WHERE [1,"2",true] != /[0-9]/; - SELECT * FROM "test" WHERE ["a","b","c"] != /[0-9]/; - - SELECT * FROM "test" WHERE [] ?= /[0-9]/; - SELECT * FROM "test" WHERE [1,2,3] ?= /[0-9]/; - SELECT * FROM "test" WHERE [1,"2",true] ?= /[0-9]/; - SELECT * FROM "test" WHERE ["a","b","c"] ?= /[0-9]/; - - SELECT * FROM "test" WHERE [] ~ "pro"; - SELECT * FROM "test" WHERE [1,2,3] ~ "pro"; - SELECT * FROM "test" WHERE [1,"2","pro"] ~ "pro"; - SELECT * FROM "test" WHERE ["a","b","c","gopros"] ~ "Pro"; - SELECT * FROM "test" WHERE ["gopros","gopros","gopros"] ~ "Pro"; - - SELECT * FROM "test" WHERE [] !~ "pro"; - SELECT * FROM "test" WHERE [1,2,3] !~ "pro"; - SELECT * FROM "test" WHERE [1,"2","pro"] !~ "pro"; - SELECT * FROM "test" WHERE ["a","b","c","gopros"] !~ "Pro"; - SELECT * FROM "test" WHERE ["gopros","gopros","gopros"] !~ "Pro"; - - SELECT * FROM "test" WHERE [] ?~ "pro"; - SELECT * FROM "test" WHERE [1,2,3] ?~ "pro"; - SELECT * FROM "test" WHERE [1,"2","pro"] ?~ "pro"; - SELECT * FROM "test" WHERE ["a","b","c","gopros"] ?~ "Pro"; - SELECT * FROM "test" WHERE ["gopros","gopros","gopros"] ?~ "Pro"; - - ` - - i := 1 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 57) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - - Convey("Check binary object comparisons", t, func() { - - setupDB(1) - - txt := ` - - USE NS test DB test; - - -- ------------------------------ - - SELECT * FROM "test" WHERE {test:true} = {test:true}; - SELECT * FROM "test" WHERE {test:true} ∈ [{test:true}]; - - -- ------------------------------ - - SELECT * FROM "test" WHERE {test:true} = {test:true}; - SELECT * FROM "test" WHERE {test:true} != {test:true}; - SELECT * FROM "test" WHERE {test:true} = {other:true}; - SELECT * FROM "test" WHERE {test:true} != {other:true}; - - ` - - i := 0 - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - So(res[inc(&i)].Result, ShouldHaveLength, 1) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 0) - So(res[inc(&i)].Result, ShouldHaveLength, 1) - - }) - -} diff --git a/db/gen.go b/db/gen.go deleted file mode 100644 index da24f263..00000000 --- a/db/gen.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -//go:generate go get -u github.com/ugorji/go/codec/codecgen -//go:generate codecgen -o db.gen.go db.go diff --git a/db/ifelse.go b/db/ifelse.go deleted file mode 100644 index fd103c99..00000000 --- a/db/ifelse.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func (e *executor) executeIfelse(ctx context.Context, stm *sql.IfelseStatement) (out []interface{}, err error) { - - val, err := e.fetchIfelse(ctx, stm, nil) - if err != nil { - return nil, err - } - - switch val := val.(type) { - case []interface{}: - out = val - case interface{}: - out = append(out, val) - } - - return - -} - -func (e *executor) fetchIfelse(ctx context.Context, stm *sql.IfelseStatement, doc *data.Doc) (interface{}, error) { - - for k, v := range stm.Cond { - ife, err := e.fetch(ctx, v, doc) - if err != nil { - return nil, err - } - if calcAsBool(ife) { - return e.fetch(ctx, stm.Then[k], doc) - } - } - - return e.fetch(ctx, stm.Else, doc) - -} diff --git a/db/ifelse_test.go b/db/ifelse_test.go deleted file mode 100644 index 040ffc5d..00000000 --- a/db/ifelse_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestIf(t *testing.T) { - - Convey("If statement which runs if clause", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..3|; - LET temp = 13.753; - IF $temp THEN - (SELECT * FROM person:1) - ELSE - (SELECT * FROM person:3) - END; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - - }) - - Convey("If statement which runs if clause", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..3|; - LET temp = 13.753; - IF $temp > 10 THEN - (SELECT * FROM person:1) - ELSE IF $temp > 5 THEN - (SELECT * FROM person:2) - ELSE - (SELECT * FROM person:3) - END; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - - }) - - Convey("If statement which runs elif clause", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..3|; - LET temp = 7.1374; - IF $temp > 10 THEN - (SELECT * FROM person:1) - ELSE IF $temp > 5 THEN - (SELECT * FROM person:2) - ELSE - (SELECT * FROM person:3) - END; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 2) - - }) - - Convey("If statement which runs else clause", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..3|; - LET temp = true; - IF $temp > 10 THEN - (SELECT * FROM person:1) - ELSE IF $temp > 5 THEN - (SELECT * FROM person:2) - ELSE - (SELECT * FROM person:3) - END; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 3) - - }) - -} diff --git a/db/info.go b/db/info.go deleted file mode 100644 index 9f6ef5db..00000000 --- a/db/info.go +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func (e *executor) executeInfo(ctx context.Context, ast *sql.InfoStatement) (out []interface{}, err error) { - - switch ast.Kind { - case sql.ALL: - return e.executeInfoKV(ctx, ast) - case sql.NAMESPACE, sql.NS: - return e.executeInfoNS(ctx, ast) - case sql.DATABASE, sql.DB: - return e.executeInfoDB(ctx, ast) - case sql.SCOPE: - return e.executeInfoSC(ctx, ast) - case sql.TABLE: - return e.executeInfoTB(ctx, ast) - } - - return - -} - -func (e *executor) executeInfoKV(ctx context.Context, ast *sql.InfoStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthKV); err != nil { - return nil, err - } - - ns, err := e.tx.AllNS(ctx) - if err != nil { - return nil, err - } - - res := data.New() - - nspac := make(map[string]interface{}) - for _, v := range ns { - nspac[v.Name.VA] = v.String() - } - - res.Set(nspac, "namespace") - - return []interface{}{res.Data()}, nil - -} - -func (e *executor) executeInfoNS(ctx context.Context, ast *sql.InfoStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - db, err := e.tx.AllDB(ctx, e.ns) - if err != nil { - return nil, err - } - - nt, err := e.tx.AllNT(ctx, e.ns) - if err != nil { - return nil, err - } - - nu, err := e.tx.AllNU(ctx, e.ns) - if err != nil { - return nil, err - } - - res := data.New() - - dbase := make(map[string]interface{}) - for _, v := range db { - dbase[v.Name.VA] = v.String() - } - - token := make(map[string]interface{}) - for _, v := range nt { - token[v.Name.VA] = v.String() - } - - login := make(map[string]interface{}) - for _, v := range nu { - login[v.User.VA] = v.String() - } - - res.Set(dbase, "database") - res.Set(token, "token") - res.Set(login, "login") - - return []interface{}{res.Data()}, nil - -} - -func (e *executor) executeInfoDB(ctx context.Context, ast *sql.InfoStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - tb, err := e.tx.AllTB(ctx, e.ns, e.db) - if err != nil { - return nil, err - } - - dt, err := e.tx.AllDT(ctx, e.ns, e.db) - if err != nil { - return nil, err - } - - du, err := e.tx.AllDU(ctx, e.ns, e.db) - if err != nil { - return nil, err - } - - sc, err := e.tx.AllSC(ctx, e.ns, e.db) - if err != nil { - return nil, err - } - - res := data.New() - - table := make(map[string]interface{}) - for _, v := range tb { - table[v.Name.VA] = v.String() - } - - token := make(map[string]interface{}) - for _, v := range dt { - token[v.Name.VA] = v.String() - } - - login := make(map[string]interface{}) - for _, v := range du { - login[v.User.VA] = v.String() - } - - scope := make(map[string]interface{}) - for _, v := range sc { - scope[v.Name.VA] = v.String() - } - - res.Set(table, "table") - res.Set(token, "token") - res.Set(login, "login") - res.Set(scope, "scope") - - return []interface{}{res.Data()}, nil - -} - -func (e *executor) executeInfoSC(ctx context.Context, ast *sql.InfoStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - st, err := e.tx.AllST(ctx, e.ns, e.db, ast.What.VA) - if err != nil { - return nil, err - } - - res := data.New() - - token := make(map[string]interface{}) - for _, v := range st { - token[v.Name.VA] = v.String() - } - - res.Set(token, "token") - - return []interface{}{res.Data()}, nil - -} - -func (e *executor) executeInfoTB(ctx context.Context, ast *sql.InfoStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - ev, err := e.tx.AllEV(ctx, e.ns, e.db, ast.What.VA) - if err != nil { - return nil, err - } - - fd, err := e.tx.AllFD(ctx, e.ns, e.db, ast.What.VA) - if err != nil { - return nil, err - } - - ix, err := e.tx.AllIX(ctx, e.ns, e.db, ast.What.VA) - if err != nil { - return nil, err - } - - ft, err := e.tx.AllFT(ctx, e.ns, e.db, ast.What.VA) - if err != nil { - return nil, err - } - - lv, err := e.tx.AllLV(ctx, e.ns, e.db, ast.What.VA) - if err != nil { - return nil, err - } - - res := data.New() - - event := make(map[string]interface{}) - for _, v := range ev { - event[v.Name.VA] = v.String() - } - - field := make(map[string]interface{}) - for _, v := range fd { - field[v.Name.VA] = v.String() - } - - index := make(map[string]interface{}) - for _, v := range ix { - index[v.Name.VA] = v.String() - } - - table := make(map[string]interface{}) - for _, v := range ft { - table[v.Name.VA] = v.String() - } - - lives := make(map[string]interface{}) - for _, v := range lv { - lives[v.ID] = v.String() - } - - res.Set(event, "event") - res.Set(field, "field") - res.Set(index, "index") - res.Set(table, "table") - res.Set(lives, "lives") - - return []interface{}{res.Data()}, nil - -} diff --git a/db/info_test.go b/db/info_test.go deleted file mode 100644 index fe97d1a0..00000000 --- a/db/info_test.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestInfo(t *testing.T) { - - Convey("Info for namespace", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE LOGIN test ON NAMESPACE PASSWORD "test"; - DEFINE LOGIN test ON NAMESPACE PASSHASH "$2a$10$mofTMm4nilzRSZuU0GyuCuAgHy2mEPeNRqHZH9ETnh.O1MBjy2PDO"; - DEFINE TOKEN test ON NAMESPACE TYPE HS512 VALUE "test"; - DEFINE DATABASE test; - INFO FOR NAMESPACE; - REMOVE LOGIN test ON NAMESPACE; - REMOVE TOKEN test ON NAMESPACE; - REMOVE DATABASE test; - INFO FOR NAMESPACE; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 10) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Status, ShouldEqual, "OK") - So(data.Consume(res[5].Result[0]).Get("login").Data(), ShouldHaveLength, 1) - So(data.Consume(res[5].Result[0]).Get("login.test").Data(), ShouldEqual, `DEFINE LOGIN test ON NAMESPACE PASSHASH "$2a$10$mofTMm4nilzRSZuU0GyuCuAgHy2mEPeNRqHZH9ETnh.O1MBjy2PDO"`) - So(data.Consume(res[5].Result[0]).Get("token").Data(), ShouldHaveLength, 1) - So(data.Consume(res[5].Result[0]).Get("token.test").Data(), ShouldEqual, `DEFINE TOKEN test ON NAMESPACE TYPE HS512 VALUE "test"`) - So(data.Consume(res[5].Result[0]).Get("database").Data(), ShouldHaveLength, 1) - So(data.Consume(res[5].Result[0]).Get("database.test").Data(), ShouldEqual, "DEFINE DATABASE test") - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Status, ShouldEqual, "OK") - So(res[8].Status, ShouldEqual, "OK") - So(res[9].Status, ShouldEqual, "OK") - So(data.Consume(res[9].Result[0]).Get("login").Data(), ShouldHaveLength, 0) - So(data.Consume(res[9].Result[0]).Get("token").Data(), ShouldHaveLength, 0) - So(data.Consume(res[9].Result[0]).Get("database").Data(), ShouldHaveLength, 0) - - }) - - Convey("Info for database", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE LOGIN test ON DATABASE PASSWORD "test"; - DEFINE LOGIN test ON DATABASE PASSHASH "$2a$10$mofTMm4nilzRSZuU0GyuCuAgHy2mEPeNRqHZH9ETnh.O1MBjy2PDO"; - DEFINE TOKEN test ON DATABASE TYPE HS512 VALUE "test"; - DEFINE SCOPE test; - DEFINE TABLE test; - INFO FOR DATABASE; - REMOVE LOGIN test ON DATABASE; - REMOVE TOKEN test ON DATABASE; - REMOVE SCOPE test; - REMOVE TABLE test; - INFO FOR DATABASE; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 12) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Status, ShouldEqual, "OK") - So(data.Consume(res[6].Result[0]).Get("login").Data(), ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("login.test").Data(), ShouldEqual, `DEFINE LOGIN test ON DATABASE PASSHASH "$2a$10$mofTMm4nilzRSZuU0GyuCuAgHy2mEPeNRqHZH9ETnh.O1MBjy2PDO"`) - So(data.Consume(res[6].Result[0]).Get("token").Data(), ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("token.test").Data(), ShouldEqual, `DEFINE TOKEN test ON DATABASE TYPE HS512 VALUE "test"`) - So(data.Consume(res[6].Result[0]).Get("scope").Data(), ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("scope.test").Data(), ShouldEqual, "DEFINE SCOPE test") - So(data.Consume(res[6].Result[0]).Get("table").Data(), ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("table.test").Data(), ShouldEqual, "DEFINE TABLE test") - So(res[7].Status, ShouldEqual, "OK") - So(res[8].Status, ShouldEqual, "OK") - So(res[9].Status, ShouldEqual, "OK") - So(res[10].Status, ShouldEqual, "OK") - So(res[11].Status, ShouldEqual, "OK") - So(data.Consume(res[11].Result[0]).Get("login").Data(), ShouldHaveLength, 0) - So(data.Consume(res[11].Result[0]).Get("token").Data(), ShouldHaveLength, 0) - So(data.Consume(res[11].Result[0]).Get("scope").Data(), ShouldHaveLength, 0) - So(data.Consume(res[11].Result[0]).Get("table").Data(), ShouldHaveLength, 0) - - }) - - Convey("Info for scope", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE SCOPE test; - DEFINE TOKEN test ON SCOPE test TYPE HS512 VALUE "test"; - INFO FOR SCOPE test; - REMOVE TOKEN test ON SCOPE test; - INFO FOR SCOPE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(data.Consume(res[3].Result[0]).Get("token").Data(), ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("token.test").Data(), ShouldEqual, `DEFINE TOKEN test ON SCOPE test TYPE HS512 VALUE "test"`) - So(res[4].Status, ShouldEqual, "OK") - So(res[5].Status, ShouldEqual, "OK") - So(data.Consume(res[5].Result[0]).Get("token").Data(), ShouldHaveLength, 0) - - }) - - Convey("Info for table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON test WHEN true THEN (CREATE test); - DEFINE FIELD test ON test; - DEFINE INDEX test ON test COLUMNS id; - INFO FOR TABLE test; - REMOVE EVENT test ON test; - REMOVE FIELD test ON test; - REMOVE INDEX test ON test; - INFO FOR TABLE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "OK") - So(data.Consume(res[4].Result[0]).Get("event").Data(), ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("event.test").Data(), ShouldEqual, "DEFINE EVENT test ON test WHEN true THEN (CREATE test)") - So(data.Consume(res[4].Result[0]).Get("field").Data(), ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("field.test").Data(), ShouldEqual, "DEFINE FIELD test ON test") - So(data.Consume(res[4].Result[0]).Get("index").Data(), ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("index.test").Data(), ShouldEqual, "DEFINE INDEX test ON test COLUMNS id") - So(res[5].Status, ShouldEqual, "OK") - So(res[6].Status, ShouldEqual, "OK") - So(res[7].Status, ShouldEqual, "OK") - So(res[8].Status, ShouldEqual, "OK") - So(data.Consume(res[8].Result[0]).Get("event").Data(), ShouldHaveLength, 0) - So(data.Consume(res[8].Result[0]).Get("field").Data(), ShouldHaveLength, 0) - So(data.Consume(res[8].Result[0]).Get("index").Data(), ShouldHaveLength, 0) - - }) - -} diff --git a/db/insert.go b/db/insert.go deleted file mode 100644 index 81fd08f2..00000000 --- a/db/insert.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeInsert(ctx context.Context, stm *sql.InsertStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - data, err := e.fetch(ctx, stm.Data, nil) - if err != nil { - return nil, err - } - - i := newIterator(e, ctx, stm, false) - - switch data := data.(type) { - - default: - return nil, fmt.Errorf("Can not execute INSERT query using value '%v'", data) - - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: stm.Into.TB} - i.processArray(ctx, key, data) - - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: stm.Into.TB} - i.processArray(ctx, key, []interface{}{data}) - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchInsert(ctx context.Context, stm *sql.InsertStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeInsert(ctx, stm) - if err != nil { - return nil, err - } - - switch len(out) { - case 1: - return data.Consume(out).Get(docKeyOne, docKeyId).Data(), nil - default: - return data.Consume(out).Get(docKeyAll, docKeyId).Data(), nil - } - -} - -func (d *document) runInsert(ctx context.Context, stm *sql.InsertStatement) (interface{}, error) { - - var ok bool - var err error - var met = _CREATE - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.lock(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.val.Exi() == true { - return nil, &ExistError{exist: d.id} - } - - if err = d.merge(ctx, met, nil); err != nil { - return nil, err - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.storeIndex(ctx); err != nil { - return nil, err - } - - if err = d.storeThing(ctx); err != nil { - return nil, err - } - - if err = d.table(ctx, met); err != nil { - return nil, err - } - - if err = d.lives(ctx, met); err != nil { - return nil, err - } - - if err = d.event(ctx, met); err != nil { - return nil, err - } - - return d.yield(ctx, stm, stm.Echo) - -} diff --git a/db/insert_test.go b/db/insert_test.go deleted file mode 100644 index b0d268d1..00000000 --- a/db/insert_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestInsert(t *testing.T) { - - Convey("Insert with invalid value", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - INSERT 1 INTO user; - INSERT "one" INTO user; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Status, ShouldEqual, "ERR") - So(res[1].Detail, ShouldEqual, "Can not execute INSERT query using value '1'") - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Can not execute INSERT query using value 'one'") - - }) - - Convey("Insert a set of ids from one table to another table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - INSERT (SELECT id FROM person) INTO user; - SELECT * FROM person, user; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - So(res[5].Result, ShouldHaveLength, 6) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 1)) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 2)) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 3)) - So(data.Consume(res[5].Result[3]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[3]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[5].Result[4]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[4]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[5].Result[5]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[5]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - - }) - - Convey("Insert a set of records from one table to another table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - INSERT (SELECT * FROM person) INTO user; - SELECT * FROM person, user; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[4].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[4].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[4].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - So(res[5].Result, ShouldHaveLength, 6) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 1)) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 2)) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 3)) - So(data.Consume(res[5].Result[3]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[3]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[5].Result[4]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[4]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[5].Result[5]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[5]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - - }) - - Convey("Insert a set of records from data with an ID", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = { "id": 360, "admin":true, "login":"joe" }; - INSERT $data INTO users; - INSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - So(res[3].Status, ShouldEqual, "ERR_EX") - So(res[3].Detail, ShouldEqual, "Database record 'users:360' already exists") - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - - }) - - Convey("Insert a set of records from data without an ID", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = { "admin":true, "login":"tom" }; - INSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - - }) - - Convey("Insert a set of records from an array of data with IDs", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = [ - { "id": 360, "admin":true, "login":"joe" }, - { "id": 200, "admin":false, "login":"mike" }, - { "id": "test", "admin":false, "login":"tester" }, - ]; - INSERT $data INTO users; - INSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 3) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - So(data.Consume(res[2].Result[1]).Get("login").Data(), ShouldEqual, "mike") - So(data.Consume(res[2].Result[1]).Get("meta.id").Data(), ShouldEqual, 200) - So(data.Consume(res[2].Result[2]).Get("login").Data(), ShouldEqual, "tester") - So(data.Consume(res[2].Result[2]).Get("meta.id").Data(), ShouldEqual, "test") - So(res[3].Status, ShouldEqual, "ERR_EX") - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("login").Data(), ShouldEqual, "mike") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, 200) - So(data.Consume(res[4].Result[1]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[4].Result[1]).Get("meta.id").Data(), ShouldEqual, 360) - So(data.Consume(res[4].Result[2]).Get("login").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[2]).Get("meta.id").Data(), ShouldEqual, "test") - - }) - - Convey("Insert a set of records from an array of data without IDs", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = [ - { "admin":true, "login":"tom" }, - ]; - INSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - - }) - -} diff --git a/db/iterator.go b/db/iterator.go deleted file mode 100644 index 3aff1bc6..00000000 --- a/db/iterator.go +++ /dev/null @@ -1,1057 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - "math" - "sort" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/comp" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/fncs" - "github.com/surrealdb/surrealdb/util/guid" - "github.com/surrealdb/surrealdb/util/ints" - "github.com/surrealdb/surrealdb/util/keys" - "github.com/surrealdb/surrealdb/util/nums" - "github.com/surrealdb/surrealdb/util/rand" -) - -type iterator struct { - e *executor - - id int - - vir bool - err error - stm sql.Statement - res []interface{} - - stop chan struct{} - - expr sql.Fields - what sql.Exprs - cond sql.Expr - split sql.Idents - group sql.Groups - order sql.Orders - limit int - start int - versn int64 -} - -type groupable struct { - doc *data.Doc - ats []interface{} -} - -type orderable struct { - doc *data.Doc - ats []interface{} -} - -func newIterator(e *executor, ctx context.Context, stm sql.Statement, vir bool) (i *iterator) { - - i = iteratorPool.Get().(*iterator) - - i.e = e - - i.id = rand.Int() - - i.vir = vir - i.err = nil - i.stm = stm - i.res = make([]interface{}, 0) - i.stop = make(chan struct{}) - - // Comment here - i.setup(ctx) - - return - -} - -func (i *iterator) Close() { - - i.e = nil - i.err = nil - i.stm = nil - i.res = nil - i.stop = nil - - i.expr = nil - i.what = nil - i.cond = nil - i.split = nil - i.group = nil - i.order = nil - i.limit = -1 - i.start = -1 - i.versn = 0 - - iteratorPool.Put(i) - -} - -func (i *iterator) setup(ctx context.Context) { - - i.expr = nil - i.what = nil - i.cond = nil - i.split = nil - i.group = nil - i.order = nil - i.limit = -1 - i.start = -1 - i.versn = math.MaxInt64 - - switch stm := i.stm.(type) { - case *sql.SelectStatement: - i.expr = stm.Expr - i.what = stm.What - i.cond = stm.Cond - i.split = stm.Split - i.group = stm.Group - i.order = stm.Order - case *sql.CreateStatement: - i.what = stm.What - case *sql.UpdateStatement: - i.what = stm.What - i.cond = stm.Cond - case *sql.DeleteStatement: - i.what = stm.What - i.cond = stm.Cond - case *sql.InsertStatement: - i.what = sql.Exprs{stm.Data} - case *sql.UpsertStatement: - i.what = sql.Exprs{stm.Data} - } - - if stm, ok := i.stm.(*sql.SelectStatement); ok { - - // Fetch and check the LIMIT BY expression - // to see if any parameter specified is valid. - - i.limit, i.err = i.e.fetchLimit(ctx, stm.Limit) - if i.err != nil { - close(i.stop) - return - } - - // Fetch and check the START AT expression - // to see if any parameter specified is valid. - - i.start, i.err = i.e.fetchStart(ctx, stm.Start) - if i.err != nil { - close(i.stop) - return - } - - // Fetch and check the VERSION expression to - // see if any parameter specified is valid. - - i.versn, i.err = i.e.fetchVersion(ctx, stm.Version) - if i.err != nil { - close(i.stop) - return - } - - } - -} - -func (i *iterator) check(ctx context.Context) bool { - - select { - case <-ctx.Done(): - return false - case <-i.stop: - return false - default: - return true - } - -} - -func (i *iterator) process(ctx context.Context, key *keys.Thing, val kvs.KV, doc *data.Doc) { - - res, err := newDocument(i, key, val, doc).query(ctx, i.stm) - - // If an error was received from the - // worker, then set the error if no - // previous iterator error has occured. - - if err != nil { - select { - case <-ctx.Done(): - return - case <-i.stop: - return - default: - i.err = err - close(i.stop) - return - } - } - - // Otherwise add the received result - // to the iterator result slice so - // that it is ready for processing. - - if res != nil { - i.res = append(i.res, res) - } - - // The statement does not have a limit - // expression specified, so therefore - // we need to load all data before - // stopping the iterator. - - if i.limit < 0 { - return - } - - // If the statement specified a GROUP - // BY expression, then we need to load - // all data from all sources before - // stopping the iterator. - - if len(i.group) > 0 { - return - } - - // If the statement specified an ORDER - // BY expression, then we need to load - // all data from all sources before - // stopping the iterator. - - if len(i.order) > 0 { - return - } - - // Otherwise we can stop the iterator - // early, if we have the necessary - // number of records specified in the - // query statement. - - select { - case <-ctx.Done(): - return - case <-i.stop: - return - default: - if i.start >= 0 { - if len(i.res) == i.limit+i.start { - close(i.stop) - } - } else { - if len(i.res) == i.limit { - close(i.stop) - } - } - } - -} - -func (i *iterator) processPerms(ctx context.Context, nsv, dbv, tbv string) { - - var tb *sql.DefineTableStatement - - // If we are authenticated using DB, NS, - // or KV permissions level, then we can - // ignore all permissions checks, but we - // must ensure the TB, DB, and NS exist. - - if perm(ctx) < cnf.AuthSC { - - // If we do not have a specified table - // value, because we are processing a - // subquery, then there is no need to - // check if the table exists or not. - - if len(tbv) == 0 { - return - } - - // If this is a select statement then - // there is no need to fetch the table - // to check whether it is a view table. - - switch i.stm.(type) { - case *sql.SelectStatement: - return - } - - // If it is not a select statement, then - // we need to fetch the table to ensure - // that the table is not a view table. - - tb, i.err = i.e.tx.AddTB(ctx, nsv, dbv, tbv) - if i.err != nil { - close(i.stop) - return - } - - // If the table is locked (because it - // has been specified as a view), then - // check to see what query type it is - // and return an error if it attempts - // to alter the table in any way. - - if tb.Lock && i.vir == false { - switch i.stm.(type) { - case *sql.CreateStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.UpdateStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.DeleteStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.RelateStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.InsertStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.UpsertStatement: - i.err = &TableError{table: tb.Name.VA} - } - } - - if i.err != nil { - close(i.stop) - } - - return - - } - - // If we do not have a specified table - // value, because we are processing a - // subquery, then there is no need to - // check if the table exists or not. - - if len(tbv) == 0 { - return - } - - // First check that the NS exists, as - // otherwise, the scoped authentication - // request can not do anything. - - _, i.err = i.e.tx.GetNS(ctx, nsv) - if i.err != nil { - close(i.stop) - return - } - - // Next check that the DB exists, as - // otherwise, the scoped authentication - // request can not do anything. - - _, i.err = i.e.tx.GetDB(ctx, nsv, dbv) - if i.err != nil { - close(i.stop) - return - } - - // Then check that the TB exists, as - // otherwise, the scoped authentication - // request can not do anything. - - tb, i.err = i.e.tx.GetTB(ctx, nsv, dbv, tbv) - if i.err != nil { - close(i.stop) - return - } - - // If the table is locked (because it - // has been specified as a view), then - // check to see what query type it is - // and return an error, if it attempts - // to alter the table in any way. - - if tb.Lock && i.vir == false { - switch i.stm.(type) { - case *sql.CreateStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.UpdateStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.DeleteStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.RelateStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.InsertStatement: - i.err = &TableError{table: tb.Name.VA} - case *sql.UpsertStatement: - i.err = &TableError{table: tb.Name.VA} - } - } - - if i.err != nil { - close(i.stop) - return - } - - // If the table does exist we then try - // to process the relevant permissions - // expression, but only if they don't - // reference any document fields. - - switch p := tb.Perms.(type) { - default: - i.err = &PermsError{table: tb.Name.VA} - case *sql.PermExpression: - switch i.stm.(type) { - case *sql.SelectStatement: - i.err = i.e.fetchPerms(ctx, p.Select, tb.Name) - case *sql.CreateStatement: - i.err = i.e.fetchPerms(ctx, p.Create, tb.Name) - case *sql.UpdateStatement: - i.err = i.e.fetchPerms(ctx, p.Update, tb.Name) - case *sql.DeleteStatement: - i.err = i.e.fetchPerms(ctx, p.Delete, tb.Name) - case *sql.RelateStatement: - i.err = i.e.fetchPerms(ctx, p.Create, tb.Name) - case *sql.InsertStatement: - i.err = i.e.fetchPerms(ctx, p.Create, tb.Name) - case *sql.UpsertStatement: - i.err = i.e.fetchPerms(ctx, p.Update, tb.Name) - } - } - - if i.err != nil { - close(i.stop) - return - } - - return - -} - -func (i *iterator) processThing(ctx context.Context, key *keys.Thing) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - if i.check(ctx) { - i.process(ctx, key, nil, nil) - } - -} - -func (i *iterator) processTable(ctx context.Context, key *keys.Table) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - // TODO use indexes to speed up queries - // We need to make use of indexes here - // so that the query speed is improved. - // If an index exists with the correct - // ORDER BY fields then iterate over - // the IDs from the index. - - beg := &keys.Thing{KV: key.KV, NS: key.NS, DB: key.DB, TB: key.TB, ID: keys.Ignore} - end := &keys.Thing{KV: key.KV, NS: key.NS, DB: key.DB, TB: key.TB, ID: keys.Suffix} - - min, max := beg.Encode(), end.Encode() - - for x := 0; ; x = 1 { - - var vals []kvs.KV - - if !i.check(ctx) { - return - } - - vals, i.err = i.e.tx.GetR(ctx, i.versn, min, max, 10000) - if i.err != nil { - close(i.stop) - return - } - - // If there are no further records - // fetched from the data layer, then - // return out of this loop iteration. - - if x >= len(vals) { - return - } - - // If there were at least 1 or 2 - // keys-values, then loop over all - // the items and process the records. - - for _, val := range vals { - if i.check(ctx) { - i.process(ctx, nil, val, nil) - continue - } - } - - // When we loop around, we will use - // the key of the last retrieved key - // to perform the next range request. - - beg.Decode(vals[len(vals)-1].Key()) - - min = append(beg.Encode(), byte(0)) - - } - -} - -func (i *iterator) processBatch(ctx context.Context, key *keys.Thing, qry *sql.Batch) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - for _, val := range qry.BA { - - // Loop over the items in the batch - // and specify the TB and ID for - // each record. - - if i.check(ctx) { - key := key.Copy() - key.TB, key.ID = val.TB, val.ID - i.process(ctx, key, nil, nil) - continue - } - - break - - } - -} - -func (i *iterator) processModel(ctx context.Context, key *keys.Thing, qry *sql.Model) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - switch { - - case qry.INC == 0: - - // If there was no incrementing pattern - // specified for the model, then let's - // generate unique ids for each record. - - for j := 1; j <= int(qry.MAX); j++ { - - if i.check(ctx) { - key := key.Copy() - key.ID = guid.New().String() - i.process(ctx, key, nil, nil) - continue - } - - break - - } - - case qry.MIN < qry.MAX: - - // If an incrementing pattern has been - // specified, then ascend through the - // steps sequentially. - - dec := nums.CountPlaces(qry.INC) - - for num := qry.MIN; num <= qry.MAX; num = nums.FormatPlaces(num+qry.INC, dec) { - - if i.check(ctx) { - key := key.Copy() - key.ID = num - i.process(ctx, key, nil, nil) - continue - } - - break - - } - - case qry.MIN > qry.MAX: - - // If an decrementing pattern has been - // specified, then descend through the - // steps sequentially. - - dec := nums.CountPlaces(qry.INC) - - for num := qry.MIN; num >= qry.MAX; num = nums.FormatPlaces(num-qry.INC, dec) { - - if i.check(ctx) { - key := key.Copy() - key.ID = num - i.process(ctx, key, nil, nil) - continue - } - - break - - } - - } - -} - -func (i *iterator) processOther(ctx context.Context, key *keys.Thing, val []interface{}) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - for _, v := range val { - - switch v := v.(type) { - - case *sql.Thing: - - // If the item is a *sql.Thing then - // this was a subquery which projected - // the ID only, and we can query the - // record further after loading it. - - if i.check(ctx) { - key := key.Copy() - key.TB, key.ID = v.TB, v.ID - i.process(ctx, key, nil, nil) - continue - } - - case map[string]interface{}: - - // If the data item has an ID field, - // then use this as the new record ID. - - if fld, ok := v["id"]; ok { - - switch thg := fld.(type) { - - case *sql.Thing: - - // If the ID is a *sql.Thing then this - // was a subquery, so use the ID. - - if i.check(ctx) { - key := key.Copy() - key.ID = thg.ID - i.process(ctx, key, nil, data.Consume(v)) - continue - } - - case string: - - // If not, then take the whole ID and - // use that as the ID of the new record. - - if i.check(ctx) { - if thg := sql.ParseThing(thg); thg != nil { - key := key.Copy() - key.TB = thg.TB - key.ID = thg.ID - fmt.Println(thg) - i.process(ctx, key, nil, data.Consume(v)) - continue - } - } - - default: - - switch i.stm.(type) { - case *sql.CreateStatement: - i.err = fmt.Errorf("Can not execute CREATE query using value '%v'", val) - case *sql.UpdateStatement: - i.err = fmt.Errorf("Can not execute UPDATE query using value '%v'", val) - case *sql.DeleteStatement: - i.err = fmt.Errorf("Can not execute DELETE query using value '%v'", val) - case *sql.RelateStatement: - i.err = fmt.Errorf("Can not execute RELATE query using value '%v'", val) - } - - close(i.stop) - - } - - } else { - - switch i.stm.(type) { - case *sql.CreateStatement: - i.err = fmt.Errorf("Can not execute CREATE query using value '%v'", val) - case *sql.UpdateStatement: - i.err = fmt.Errorf("Can not execute UPDATE query using value '%v'", val) - case *sql.DeleteStatement: - i.err = fmt.Errorf("Can not execute DELETE query using value '%v'", val) - case *sql.RelateStatement: - i.err = fmt.Errorf("Can not execute RELATE query using value '%v'", val) - } - - close(i.stop) - - } - - default: - - switch i.stm.(type) { - case *sql.CreateStatement: - i.err = fmt.Errorf("Can not execute CREATE query using value '%v'", val) - case *sql.UpdateStatement: - i.err = fmt.Errorf("Can not execute UPDATE query using value '%v'", val) - case *sql.DeleteStatement: - i.err = fmt.Errorf("Can not execute DELETE query using value '%v'", val) - case *sql.RelateStatement: - i.err = fmt.Errorf("Can not execute RELATE query using value '%v'", val) - } - - close(i.stop) - - } - - break - - } - -} - -func (i *iterator) processQuery(ctx context.Context, key *keys.Thing, val []interface{}) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - for _, v := range val { - - switch v := v.(type) { - - case *sql.Thing: - - // If the item is a *sql.Thing then - // this was a subquery which projected - // the ID only, and we can query the - // record further after loading it. - - if i.check(ctx) { - key := key.Copy() - key.TB, key.ID = v.TB, v.ID - i.process(ctx, key, nil, nil) - continue - } - - default: - - // Otherwise let's just load up all - // of the data so we can process it. - - if i.check(ctx) { - i.process(ctx, nil, nil, data.Consume(v)) - continue - } - - } - - break - - } - -} - -func (i *iterator) processArray(ctx context.Context, key *keys.Thing, val []interface{}) { - - i.processPerms(ctx, key.NS, key.DB, key.TB) - - for _, v := range val { - - switch v := v.(type) { - - case *sql.Thing: - - // If the item is a *sql.Thing then - // this was a subquery, so use the ID. - - if i.check(ctx) { - key := key.Copy() - key.ID = v.ID - i.process(ctx, key, nil, nil) - continue - } - - case map[string]interface{}: - - // If the data item has an ID field, - // then use this as the new record ID. - - if fld, ok := v["id"]; ok { - - switch thg := fld.(type) { - - case *sql.Thing: - - // If the ID is a *sql.Thing then this - // was a subquery, so use the ID. - - if i.check(ctx) { - key := key.Copy() - key.ID = thg.ID - i.process(ctx, key, nil, data.Consume(v)) - continue - } - - case string: - - // If not, then take the whole ID and - // use that as the ID of the new record. - - if i.check(ctx) { - key := key.Copy() - if thg := sql.ParseThing(thg); thg != nil { - key.TB = thg.TB - key.ID = thg.ID - } else { - key.ID = fld - } - i.process(ctx, key, nil, data.Consume(v)) - continue - } - - default: - - // If not, then take the whole ID and - // use that as the ID of the new record. - - if i.check(ctx) { - key := key.Copy() - key.ID = fld - i.process(ctx, key, nil, data.Consume(v)) - continue - } - - } - - } else { - - // If there is no ID field, then create - // a unique id for the new record. - - if i.check(ctx) { - key := key.Copy() - key.ID = guid.New().String() - i.process(ctx, key, nil, data.Consume(v)) - continue - } - - } - - } - - break - - } - -} - -func (i *iterator) Yield(ctx context.Context) (out []interface{}, err error) { - - defer i.Close() - - if i.err != nil { - return nil, i.err - } - - if len(i.split) > 0 { - i.res = i.Split(ctx, i.res) - } - - if len(i.group) > 0 { - i.res = i.Group(ctx, i.res) - } - - if len(i.order) > 0 { - i.res = i.Order(ctx, i.res) - } - - if i.start >= 0 { - num := ints.Min(i.start, len(i.res)) - i.res = i.res[num:] - } - - if i.limit >= 0 { - num := ints.Min(i.limit, len(i.res)) - i.res = i.res[:num] - } - - return i.res, i.err - -} - -func (i *iterator) Split(ctx context.Context, arr []interface{}) (out []interface{}) { - - for _, s := range i.split { - - out = make([]interface{}, 0) - - for _, a := range arr { - - doc := data.Consume(a) - - pth := make([]string, 0) - - switch doc.Get(s.VA).Data().(type) { - case []interface{}: - pth = append(pth, s.VA, docKeyAll) - default: - pth = append(pth, s.VA) - } - - doc.Walk(func(key string, val interface{}, exi bool) error { - doc := doc.Copy() - doc.Set(val, s.VA) - out = append(out, doc.Data()) - return nil - }, pth...) - - } - - arr = out - - } - - return out - -} - -func (i *iterator) Group(ctx context.Context, arr []interface{}) (out []interface{}) { - - var grp []*groupable - var col = make(map[string][]interface{}) - - // Loop through all of the items - // and create a *groupable to - // store the record, and all of - // the attributes in the GROUP BY. - - for _, a := range arr { - - g := &groupable{ - doc: data.Consume(a), - ats: make([]interface{}, len(i.group)), - } - - for k, e := range i.group { - g.ats[k], _ = i.e.fetch(ctx, e.Expr, g.doc) - } - - grp = append(grp, g) - - } - - // Group all of the items together - // according to the GROUP by clause. - // We use a string representation of - // the group fields to group records. - - for _, s := range grp { - k := fmt.Sprintf("%v", s.ats) - col[k] = append(col[k], s.doc.Data()) - } - - for _, obj := range col { - - doc, all := data.New(), data.Consume(obj) - - for _, e := range i.expr { - - // If the clause has a GROUP BY expression - // then let's check if this is an aggregate - // function, and if it is then calculate - // the output with the aggregated data. - - if f, ok := e.Expr.(*sql.FuncExpression); ok && f.Aggr { - args := make([]interface{}, len(f.Args)) - for x := 0; x < len(f.Args); x++ { - if x == 0 { - args[x] = all.Get("*", f.String()).Data() - } else { - args[x], _ = i.e.fetch(ctx, f.Args[x], nil) - } - } - val, _ := fncs.Run(ctx, f.Name, args...) - doc.Set(val, e.Field) - continue - } - - // Otherwise if not, then it is a field - // which is also specified in the GROUP BY - // clause, so let's include the first - // value in the aggregated results. - - val := all.Get("0", e.Field).Data() - doc.Set(val, e.Field) - - } - - out = append(out, doc.Data()) - - } - - return - -} - -func (i *iterator) Order(ctx context.Context, arr []interface{}) (out []interface{}) { - - var ord []*orderable - - // Loop through all of the items - // and create an *orderable to - // store the record, and all of - // the attributes in the ORDER BY. - - for _, a := range arr { - ord = append(ord, &orderable{ - doc: data.Consume(a), - ats: make([]interface{}, 0), - }) - } - - // Sort the *sortable items whilst - // fetching any values which were - // previously not loaded. Cache - // the values on the *orderable. - - sort.Slice(ord, func(k, j int) bool { - for x, e := range i.order { - if len(ord[k].ats) <= x { - a, _ := i.e.fetch(ctx, e.Expr, ord[k].doc) - ord[k].ats = append(ord[k].ats, a) - } - if len(ord[j].ats) <= x { - a, _ := i.e.fetch(ctx, e.Expr, ord[j].doc) - ord[j].ats = append(ord[j].ats, a) - } - if c := comp.Comp(ord[k].ats[x], ord[j].ats[x], e); c != 0 { - return (c < 0 && e.Dir) || (c > 0 && !e.Dir) - } - } - return false - }) - - // Loop over the sorted items and - // add the document data for each - // item to the output array. - - for _, s := range ord { - out = append(out, s.doc.Data()) - } - - return - -} diff --git a/db/let.go b/db/let.go deleted file mode 100644 index 24c1039f..00000000 --- a/db/let.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func (e *executor) executeLet(ctx context.Context, stm *sql.LetStatement) (out []interface{}, err error) { - - var vars = ctx.Value(ctxKeyVars).(*data.Doc) - - switch what := stm.What.(type) { - case *sql.Void: - vars.Del(stm.Name.VA) - case *sql.Empty: - vars.Del(stm.Name.VA) - default: - val, err := e.fetch(ctx, what, nil) - if err != nil { - return nil, err - } - vars.Set(val, stm.Name.VA) - } - - return - -} diff --git a/db/let_test.go b/db/let_test.go deleted file mode 100644 index f87fe437..00000000 --- a/db/let_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestLet(t *testing.T) { - - Convey("Let to create a new variable", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET temp = "test"; - RETURN $temp; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldResemble, []interface{}{"test"}) - - }) - - Convey("Let to create and VOID a variable", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET temp = "test"; - LET temp = VOID; - RETURN $temp; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldResemble, []interface{}{nil}) - - }) - - Convey("Let to create and EMPTY a variable", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET temp = "test"; - LET temp = EMPTY; - RETURN $temp; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldResemble, []interface{}{nil}) - - }) - -} diff --git a/db/live.go b/db/live.go deleted file mode 100644 index c7ef50cc..00000000 --- a/db/live.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "sync" - - "context" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" -) - -var sockets sync.Map - -func register(fib *fibre.Context, id string) func() { - return func() { - - sockets.Store(id, &socket{ - fibre: fib, - sends: make(map[string][]interface{}), - items: make(map[string][]interface{}), - lives: make(map[string]*sql.LiveStatement), - }) - - } -} - -func deregister(fib *fibre.Context, id string) func() { - return func() { - - if sck, ok := sockets.Load(id); ok { - sck.(*socket).deregister(id) - } - - } -} - -func (e *executor) executeLive(ctx context.Context, stm *sql.LiveStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - if sck, ok := sockets.Load(e.id); ok { - return sck.(*socket).executeLive(e, ctx, stm) - } - - return nil, &LiveError{} - -} - -func (e *executor) executeKill(ctx context.Context, stm *sql.KillStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - if sck, ok := sockets.Load(e.id); ok { - return sck.(*socket).executeKill(e, ctx, stm) - } - - return nil, &LiveError{} - -} diff --git a/db/lives.go b/db/lives.go deleted file mode 100644 index 1e7737cf..00000000 --- a/db/lives.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" -) - -// Lives checks if any table views are specified for -// this table, and executes them in name order. -func (d *document) lives(ctx context.Context, when method) (err error) { - - // Check if this query has been run - // in forced mode, because of an - // index or foreign table update. - - forced := d.forced(ctx) - - // If this document has not changed - // then there is no need to update - // any registered live queries. - - if !forced && !d.changed { - return nil - } - - // Get the foreign read-only tables - // specified for this table, and - // update values which have changed. - - lvs, err := d.i.e.tx.AllLV(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - // Loop over the currently running - // live queries so that we can pass - // change notifications to the socket. - - for _, lv := range lvs { - - // Check whether the change was made by - // the same connection as the live query, - // and if it is then don't notify changes. - - if d.i.e.id == lv.FB { - continue - } - - // Load the socket which owns the live - // query so that we can check the socket - // permissions, and send the notifications. - - if sck, ok := sockets.Load(lv.FB); ok { - - var out interface{} - - // Create a new context for this socket - // which has the correct connection - // variables, and auth levels. - - ctx = sck.(*socket).ctx() - - // Check whether this live query has the - // necessary permissions to view this - // document, or continue to the next query. - - ok, err = d.grant(ctx, when) - if err != nil { - continue - } else if !ok { - continue - } - - // Check whether this document matches the - // filter conditions for the live query and - // if not, then continue to the next query. - - ok, err = d.check(ctx, lv.Cond) - if err != nil { - continue - } else if !ok { - continue - } - - switch lv.Diff { - - // If the live query has specified to only - // receive diff changes, then there will be - // no projected fields for this query. - - case true: - - out, _ = d.yield(ctx, lv, sql.DIFF) - - // If the query has projected fields which it - // wants to receive, then let's fetch these - // fields, and return them to the socket. - - case false: - - out, _ = d.yield(ctx, lv, sql.ILLEGAL) - - } - - switch when { - case _DELETE: - sck.(*socket).queue(d.i.e.id, lv.ID, "DELETE", d.id) - case _CREATE: - if out != nil { - sck.(*socket).queue(d.i.e.id, lv.ID, "CREATE", out) - } - case _UPDATE: - if out != nil { - sck.(*socket).queue(d.i.e.id, lv.ID, "UPDATE", out) - } - } - - } - - } - - return - -} diff --git a/db/merge.go b/db/merge.go deleted file mode 100644 index 9d3044b7..00000000 --- a/db/merge.go +++ /dev/null @@ -1,444 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "sort" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/conv" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/diff" -) - -var main = map[string]struct{}{ - "id": {}, - "meta": {}, - "meta.tb": {}, - "meta.id": {}, -} - -func (d *document) merge(ctx context.Context, met method, data sql.Expr) (err error) { - - if err = d.defDoc(ctx, met); err != nil { - return - } - - if err = d.defFld(ctx, met); err != nil { - return - } - - switch expr := data.(type) { - case *sql.DataExpression: - if err = d.mrgSet(ctx, met, expr); err != nil { - return err - } - case *sql.DiffExpression: - if err = d.mrgDpm(ctx, met, expr); err != nil { - return err - } - case *sql.MergeExpression: - if err = d.mrgAny(ctx, met, expr); err != nil { - return err - } - case *sql.ContentExpression: - if err = d.mrgAll(ctx, met, expr); err != nil { - return err - } - } - - if err = d.defFld(ctx, met); err != nil { - return - } - - if err = d.mrgFld(ctx, met); err != nil { - return - } - - if err = d.defFld(ctx, met); err != nil { - return - } - - if err = d.delFld(ctx, met); err != nil { - return - } - - d.changed = d.hasChanged(ctx) - - return - -} - -func (d *document) defDoc(ctx context.Context, met method) (err error) { - - d.current = d.current.Copy() - - return - -} - -func (d *document) defFld(ctx context.Context, met method) (err error) { - - switch d.i.vir { - case true: - d.current.Set(d.id, "id") - d.current.Set(d.id.TB, "meta.tb") - d.current.Set(d.id.ID, "meta.id") - case false: - d.current.Del("meta") - d.current.Set(d.id, "id") - d.current.Set(d.id.TB, "meta.tb") - d.current.Set(d.id.ID, "meta.id") - } - - return - -} - -func (d *document) delFld(ctx context.Context, met method) (err error) { - - tb, err := d.i.e.tx.GetTB(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - if tb.Full { - - var keys = map[string]struct{}{} - - // Get the defined fields - - fds, err := d.i.e.tx.AllFD(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - // Loop over the allowed keys - - for _, fd := range fds { - d.current.Walk(func(key string, val interface{}, ok bool) (err error) { - keys[key] = struct{}{} - return - }, fd.Name.VA) - } - - // Delete any keys which aren't allowed - - d.current.Each(func(key string, val interface{}) (err error) { - if _, ok := main[key]; !ok { - if _, ok := keys[key]; !ok { - d.current.Del(key) - } - } - return - }) - - } - - return - -} - -func (d *document) mrgAll(ctx context.Context, met method, expr *sql.ContentExpression) (err error) { - - var obj map[string]interface{} - - switch v := expr.Data.(type) { - case map[string]interface{}: - obj = v - case *sql.Param: - - p, err := d.i.e.fetch(ctx, v, d.current) - if err != nil { - return err - } - - switch v := p.(type) { - case map[string]interface{}: - obj = v - } - - } - - d.current.Reset() - - for k, v := range obj { - d.current.Set(v, k) - } - - return - -} - -func (d *document) mrgAny(ctx context.Context, met method, expr *sql.MergeExpression) (err error) { - - var obj map[string]interface{} - - switch v := expr.Data.(type) { - case map[string]interface{}: - obj = v - case *sql.Param: - - p, err := d.i.e.fetch(ctx, v, d.current) - if err != nil { - return err - } - - switch v := p.(type) { - case map[string]interface{}: - obj = v - } - - } - - for k, v := range obj { - d.current.Set(v, k) - } - - return - -} - -func (d *document) mrgDpm(ctx context.Context, met method, expr *sql.DiffExpression) (err error) { - - var obj []interface{} - var old map[string]interface{} - var now map[string]interface{} - - switch v := expr.Data.(type) { - case []interface{}: - obj = v - case *sql.Param: - - p, err := d.i.e.fetch(ctx, v, d.current) - if err != nil { - return err - } - - switch v := p.(type) { - case []interface{}: - obj = v - } - - } - - old = d.current.Data().(map[string]interface{}) - now = diff.Patch(old, obj) - - d.current = data.Consume(now) - - return - -} - -func (d *document) mrgSet(ctx context.Context, met method, expr *sql.DataExpression) (err error) { - - for _, v := range expr.Data { - - if i, ok := v.LHS.(*sql.Ident); ok { - - n, err := d.i.e.fetch(ctx, v.RHS, d.current) - if err != nil { - return err - } - - switch v.Op { - case sql.EQ: - switch n.(type) { - default: - d.current.Set(n, i.VA) - case *sql.Void: - d.current.Del(i.VA) - } - case sql.INC: - d.current.Inc(n, i.VA) - case sql.DEC: - d.current.Dec(n, i.VA) - } - - } - - } - - return - -} - -func (d *document) mrgFld(ctx context.Context, met method) (err error) { - - fds, err := d.i.e.tx.AllFD(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - // Sort the fields according to their - // priority so that fields which depend - // on another field can be processed - // after that field in a specific order. - - sort.Slice(fds, func(i, j int) bool { - return fds[i].Priority < fds[j].Priority - }) - - // Loop through each field and check to - // see if it might be a specific type. - // This is because when updating records - // using json, there is no specific type - // for a 'datetime' and 'record'. - - d.current.Each(func(key string, val interface{}) (err error) { - if val, ok := conv.MightBe(val); ok { - d.current.Iff(val, key) - } - return nil - }) - - // Loop over each of the defined fields - // and process them fully, applying the - // VALUE and ASSERT clauses sequentially. - - for _, fd := range fds { - - err = d.current.Walk(func(key string, val interface{}, exi bool) error { - - var old = d.initial.Get(key).Data() - - // Ensure object and arrays are set - - val = conv.MustBe(fd.Type, val) - - // We are setting the value of the field - - if fd.Value != nil && d.i.e.opts.fields { - - // Reset the variables - - vars := data.New() - vars.Set(val, varKeyValue) - vars.Set(val, varKeyAfter) - vars.Set(old, varKeyBefore) - ctx = context.WithValue(ctx, ctxKeySpec, vars) - - if now, err := d.i.e.fetch(ctx, fd.Value, d.current); err != nil { - return err - } else { - val = now - } - - } - - // Ensure the field is the correct type - - if val != nil { - if now, err := conv.ConvertTo(fd.Type, fd.Kind, val); err != nil { - val = nil - } else { - val = now - } - } - - // We are checking the value of the field - - if fd.Assert != nil && d.i.e.opts.fields { - - // Reset the variables - - vars := data.New() - vars.Set(val, varKeyValue) - vars.Set(val, varKeyAfter) - vars.Set(old, varKeyBefore) - ctx = context.WithValue(ctx, ctxKeySpec, vars) - - if chk, err := d.i.e.fetch(ctx, fd.Assert, d.current); err != nil { - return err - } else if chk, ok := chk.(bool); ok && !chk { - return &FieldError{field: key, found: val, check: fd.Assert} - } - - } - - // We are checking the permissions of the field - - if fd.Perms != nil && perm(ctx) > cnf.AuthDB { - - // Reset the variables - - vars := data.New() - vars.Set(val, varKeyValue) - vars.Set(val, varKeyAfter) - vars.Set(old, varKeyBefore) - ctx = context.WithValue(ctx, ctxKeySpec, vars) - - switch p := fd.Perms.(type) { - case *sql.PermExpression: - switch met { - case _CREATE: - if v, err := d.i.e.fetch(ctx, p.Create, d.current); err != nil { - return err - } else { - if b, ok := v.(bool); !ok || !b { - val = old - } - } - case _UPDATE: - if v, err := d.i.e.fetch(ctx, p.Update, d.current); err != nil { - return err - } else { - if b, ok := v.(bool); !ok || !b { - val = old - } - } - case _DELETE: - if v, err := d.i.e.fetch(ctx, p.Delete, d.current); err != nil { - return err - } else { - if b, ok := v.(bool); !ok || !b { - val = old - } - } - } - } - - } - - // We are setting the value of the field - - switch val.(type) { - default: - if exi { - d.current.Set(val, key) - } else { - d.current.Iff(val, key) - } - case *sql.Void: - d.current.Del(key) - } - - return nil - - }, fd.Name.VA) - - if err != nil { - return - } - - } - - return - -} diff --git a/db/mutex.go b/db/mutex.go deleted file mode 100644 index 5b90f826..00000000 --- a/db/mutex.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - "fmt" - "sync" - "sync/atomic" -) - -type mutex struct { - m sync.Map -} - -type value struct { - v uint32 - q chan struct{} - l chan struct{} -} - -func (m *mutex) Lock(ctx context.Context, key fmt.Stringer) { - - _, v := m.item(ctx, key) - - select { - case <-ctx.Done(): - return - case <-v.q: - return - case v.l <- struct{}{}: - atomic.StoreUint32(&v.v, vers(ctx)) - return - default: - if atomic.LoadUint32(&v.v) < vers(ctx) { - close(v.q) - panic(errRaceCondition) - } - } - - select { - case <-ctx.Done(): - return - case <-v.q: - return - case v.l <- struct{}{}: - atomic.StoreUint32(&v.v, vers(ctx)) - return - } - -} - -func (m *mutex) Unlock(ctx context.Context, key fmt.Stringer) { - - _, v := m.item(ctx, key) - - select { - case <-ctx.Done(): - return - case <-v.q: - return - case <-v.l: - return - } - -} - -func (m *mutex) item(ctx context.Context, key fmt.Stringer) (string, *value) { - k := key.String() - v, _ := m.m.LoadOrStore(k, &value{ - v: vers(ctx), - q: make(chan struct{}), - l: make(chan struct{}, 1), - }) - return k, v.(*value) -} diff --git a/db/mutex_test.go b/db/mutex_test.go deleted file mode 100644 index 8eb94e5b..00000000 --- a/db/mutex_test.go +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - "sync" - "testing" - - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -type stringer struct{} - -func (this stringer) String() string { - return "test" -} - -func TestMutex(t *testing.T) { - - var n = 10 - - Convey("Context diving works correctly", t, func() { - - ctx := context.Background() - - So(vers(ctx), ShouldEqual, 0) - - for i := vers(ctx); i <= maxRecursiveQueries; i++ { - So(func() { ctx = dive(ctx) }, ShouldNotPanic) - So(vers(ctx), ShouldEqual, i+1) - } - - So(func() { dive(ctx) }, ShouldPanicWith, errRecursiveOverload) - - }) - - Convey("Allow basic mutex", t, func() { - - m := new(mutex) - ctx := context.Background() - - m.Lock(ctx, new(stringer)) - m.Unlock(ctx, new(stringer)) - - }) - - Convey("Allow concurrent mutex", t, func() { - - m := new(mutex) - wg := new(sync.WaitGroup) - ctx := context.Background() - - wg.Add(n) - - for i := 0; i < n; i++ { - go func() { - defer wg.Done() - m.Lock(ctx, new(stringer)) - m.Unlock(ctx, new(stringer)) - }() - } - - wg.Wait() - - So(nil, ShouldBeNil) - - }) - - Convey("Allow fixed-level mutex", t, func() { - - m := new(mutex) - ctx := context.Background() - - for i := 0; i < n; i++ { - ctx = dive(ctx) - So(func() { m.Lock(ctx, new(stringer)) }, ShouldNotPanic) - So(func() { m.Unlock(ctx, new(stringer)) }, ShouldNotPanic) - } - - So(nil, ShouldBeNil) - - }) - - Convey("Prevent nested-recursive mutex", t, func() { - - m := new(mutex) - ctx := context.Background() - - m.Lock(ctx, new(stringer)) - ctx = dive(ctx) - So(func() { m.Lock(ctx, new(stringer)) }, ShouldPanic) - So(func() { m.Unlock(ctx, new(stringer)) }, ShouldNotPanic) - So(func() { m.Unlock(ctx, new(stringer)) }, ShouldNotPanic) - - So(nil, ShouldBeNil) - - }) - - Convey("Ensure document locking when multiple events attempt to write to the same document", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT created ON person WHEN $method = "CREATE" THEN (UPDATE $after.fk SET fks += $this); - DEFINE EVENT deleted ON person WHEN $method = "DELETE" THEN (UPDATE $before.fk SET fks -= $this); - UPDATE |person:1..100| SET fk = other:test; - SELECT * FROM other; - DELETE FROM person; - SELECT * FROM other; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 100) - So(res[4].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("fks").Data(), ShouldHaveLength, 100) - So(res[5].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 0) - So(res[6].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("fks").Data(), ShouldHaveLength, 0) - - }) - - Convey("Ability to select the same document in a SELECT subquery", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE person:test; - SELECT * FROM (SELECT * FROM (SELECT * FROM person)); - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - - }) - - Convey("Ability to update the same document in a SELECT subquery", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE person:test; - SELECT * FROM (UPDATE person SET test=true); - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(data.Consume(res[2].Result[0]).Get("temp").Data(), ShouldBeNil) - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("temp").Data(), ShouldBeNil) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, true) - - }) - - Convey("Ability to update the same document in a SELECT subquery", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE person:test; - SELECT *, (UPDATE $parent.id SET test=true) AS test FROM person; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("temp").Data(), ShouldBeNil) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, true) - - }) - - Convey("Inability to update the same document in an UPDATE subquery", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE person:test; - UPDATE person SET temp = (UPDATE person SET test=true); - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Failed to update the same document recursively") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldBeNil) - So(data.Consume(res[3].Result[0]).Get("temp").Data(), ShouldBeNil) - - }) - - Convey("Ability to update the same document in an event", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $before.test != $after.test THEN (UPDATE $this SET temp = true); - UPDATE person:test SET test=true; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(data.Consume(res[2].Result[0]).Get("temp").Data(), ShouldBeNil) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, true) - So(res[3].Status, ShouldEqual, "OK") - So(data.Consume(res[3].Result[0]).Get("temp").Data(), ShouldEqual, true) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, true) - - }) - - Convey("Subqueries for an event should be on the same level", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $method = "CREATE" THEN (CREATE tester); - CREATE |person:100|; - SELECT * FROM person; - SELECT * FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 100) - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 100) - So(res[4].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 100) - - }) - - Convey("Subqueries for an event on a different level create an infinite loop", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $method = "CREATE" THEN (CREATE person); - CREATE person:test; - SELECT * FROM person; - SELECT * FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Infinite loop when running recursive subqueries") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 0) - So(res[4].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 0) - - }) - - Convey("Subqueries for recursive events on a different level create an infinite loop", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - DEFINE EVENT test ON person WHEN $method = "UPDATE" THEN (UPDATE tester SET temp=time.now()); - DEFINE EVENT test ON tester WHEN $method = "UPDATE" THEN (UPDATE person SET temp=time.now()); - CREATE person:test, tester:test SET temp=time.now(); - UPDATE person:test SET temp=time.now(); - SELECT * FROM person; - SELECT * FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "ERR") - So(res[4].Detail, ShouldEqual, "Infinite loop when running recursive subqueries") - So(res[5].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 1) - - }) - - Convey("Ability to define complex dependent events which should run consecutively and succeed", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE global:test SET tests=[], temps=[]; - DEFINE EVENT test ON tester WHEN $after.global != EMPTY THEN ( - UPDATE $after.global SET tests+=$this; - UPDATE temper SET tester=$this, global=$after.global; - ); - DEFINE EVENT test ON temper WHEN $after.global != EMPTY THEN ( - UPDATE $after.global SET temps+=$this; - ); - CREATE |temper:1..5|; - CREATE tester:test SET global=global:test; - SELECT * FROM global; - SELECT * FROM tester; - SELECT * FROM temper; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[4].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 5) - So(res[5].Status, ShouldEqual, "OK") - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Status, ShouldEqual, "OK") - So(res[6].Result, ShouldHaveLength, 1) - So(res[7].Status, ShouldEqual, "OK") - So(res[7].Result, ShouldHaveLength, 1) - So(res[8].Status, ShouldEqual, "OK") - So(res[8].Result, ShouldHaveLength, 5) - - }) - -} diff --git a/db/opt.go b/db/opt.go deleted file mode 100644 index edb855f8..00000000 --- a/db/opt.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - "strings" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" -) - -type options struct { - fields bool - events bool - tables bool -} - -func newOptions() *options { - return &options{ - fields: true, - events: true, - tables: true, - } -} - -func (e *executor) executeOpt(ctx context.Context, stm *sql.OptStatement) (out []interface{}, err error) { - - if perm(ctx) >= cnf.AuthSC { - return nil, new(QueryError) - } - - switch strings.ToUpper(stm.Name) { - case "FIELD_QUERIES": - e.opts.fields = stm.What - case "EVENT_QUERIES": - e.opts.events = stm.What - case "TABLE_QUERIES": - e.opts.tables = stm.What - case "IMPORT": - switch stm.What { - case true: - e.opts.fields = false // Set field queries - e.opts.events = false // Set event queries - e.opts.tables = true // Set table queries - case false: - e.opts.fields = true // Set field queries - e.opts.events = true // Set event queries - e.opts.tables = true // Set table queries - } - } - - return - -} diff --git a/db/perms.go b/db/perms.go deleted file mode 100644 index e826627e..00000000 --- a/db/perms.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func (d *document) perms(ctx context.Context, doc *data.Doc) (err error) { - - // If this is a document loaded from - // a subquery or data param, and not - // from the KV store, then there is - // no need to check permissions. - - if d.key == nil { - return nil - } - - // If we are authenticated using DB, NS, - // or KV permissions level, then we can - // ignore all permissions checks. - - if perm(ctx) < cnf.AuthSC { - return nil - } - - // Get the field definitions so we can - // check if the permissions allow us - // to view each field. - - fds, err := d.i.e.tx.AllFD(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - // Once we have the table we reset the - // context to DB level so that no other - // embedded permissions are checked on - // records within these permissions. - - ctx = context.WithValue(ctx, ctxKeyKind, cnf.AuthDB) - - // We then try to process the relevant - // permissions dependent on the query - // that we are currently processing. If - // there are no permissions specified - // for this table, then because this is - // a scoped request, return an error. - - for _, fd := range fds { - - if fd.Perms != nil { - - err = doc.Walk(func(key string, val interface{}, exi bool) error { - - // We are checking the permissions of the field - - if p, ok := fd.Perms.(*sql.PermExpression); ok { - - vars := data.New() - vars.Set(val, varKeyValue) - ctx = context.WithValue(ctx, ctxKeySpec, vars) - - if v, err := d.i.e.fetch(ctx, p.Select, doc); err != nil { - return err - } else if b, ok := v.(bool); !ok || !b { - doc.Del(key) - } - - } - - return nil - - }, fd.Name.VA) - - } - - } - - return nil - -} diff --git a/db/pool.go b/db/pool.go deleted file mode 100644 index f0aa31a8..00000000 --- a/db/pool.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import "sync" - -var executorPool = sync.Pool{ - New: func() interface{} { - return new(executor) - }, -} - -var iteratorPool = sync.Pool{ - New: func() interface{} { - return new(iterator) - }, -} - -var documentPool = sync.Pool{ - New: func() interface{} { - return new(document) - }, -} diff --git a/db/relate.go b/db/relate.go deleted file mode 100644 index df75384e..00000000 --- a/db/relate.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/guid" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeRelate(ctx context.Context, stm *sql.RelateStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - var from, with sql.Exprs - - for _, val := range stm.From { - f, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - from = append(from, f) - } - - for _, val := range stm.With { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - with = append(with, w) - } - - i := newIterator(e, ctx, stm, false) - - switch what := stm.Type.(type) { - - default: - return nil, fmt.Errorf("Can not execute RELATE query using value '%v'", what) - - case *sql.Table: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: guid.New().String()} - i.processThing(ctx, key) - - case *sql.Ident: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.VA, ID: guid.New().String()} - i.processThing(ctx, key) - - // Result of subquery - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, what) - - // Result of subquery with LIMIT 1 - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, []interface{}{what}) - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchRelate(ctx context.Context, stm *sql.RelateStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeRelate(ctx, stm) - if err != nil { - return nil, err - } - - switch len(out) { - case 1: - return data.Consume(out).Get(docKeyOne, docKeyId).Data(), nil - default: - return data.Consume(out).Get(docKeyAll, docKeyId).Data(), nil - } - -} - -func (d *document) runRelate(ctx context.Context, stm *sql.RelateStatement) (interface{}, error) { - - var ok bool - var err error - var met = _CREATE - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.lock(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.val.Exi() == true { - met = _UPDATE - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.merge(ctx, met, stm.Data); err != nil { - return nil, err - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.storeIndex(ctx); err != nil { - return nil, err - } - - if err = d.storeThing(ctx); err != nil { - return nil, err - } - - if err = d.table(ctx, met); err != nil { - return nil, err - } - - if err = d.lives(ctx, met); err != nil { - return nil, err - } - - if err = d.event(ctx, met); err != nil { - return nil, err - } - - return d.yield(ctx, stm, stm.Echo) - -} diff --git a/db/remove.go b/db/remove.go deleted file mode 100644 index 43c93544..00000000 --- a/db/remove.go +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeRemoveNamespace(ctx context.Context, ast *sql.RemoveNamespaceStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthKV); err != nil { - return nil, err - } - - e.tx.DelNS(ast.Name.VA) - - // Remove the namespace definition - nkey := &keys.NS{KV: KV, NS: ast.Name.VA} - _, err = e.tx.Clr(ctx, nkey.Encode()) - - // Remove the namespace resource data - akey := &keys.Namespace{KV: KV, NS: ast.Name.VA} - _, err = e.tx.ClrP(ctx, akey.Encode(), 0) - - return - -} - -func (e *executor) executeRemoveDatabase(ctx context.Context, ast *sql.RemoveDatabaseStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - e.tx.DelDB(e.ns, ast.Name.VA) - - // Remove the database definition - dkey := &keys.DB{KV: KV, NS: e.ns, DB: ast.Name.VA} - _, err = e.tx.Clr(ctx, dkey.Encode()) - - // Remove the database resource data - akey := &keys.Database{KV: KV, NS: e.ns, DB: ast.Name.VA} - _, err = e.tx.ClrP(ctx, akey.Encode(), 0) - - return - -} - -func (e *executor) executeRemoveLogin(ctx context.Context, ast *sql.RemoveLoginStatement) (out []interface{}, err error) { - - switch ast.Kind { - case sql.NAMESPACE: - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - // Remove the login definition - ukey := &keys.NU{KV: KV, NS: e.ns, US: ast.User.VA} - _, err = e.tx.ClrP(ctx, ukey.Encode(), 0) - - case sql.DATABASE: - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - // Remove the login definition - ukey := &keys.DU{KV: KV, NS: e.ns, DB: e.db, US: ast.User.VA} - _, err = e.tx.ClrP(ctx, ukey.Encode(), 0) - - } - - return - -} - -func (e *executor) executeRemoveToken(ctx context.Context, ast *sql.RemoveTokenStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - switch ast.Kind { - case sql.NAMESPACE: - - if err := e.access(ctx, cnf.AuthNS); err != nil { - return nil, err - } - - // Remove the token definition - tkey := &keys.NT{KV: KV, NS: e.ns, TK: ast.Name.VA} - _, err = e.tx.ClrP(ctx, tkey.Encode(), 0) - - case sql.DATABASE: - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - // Remove the token definition - tkey := &keys.DT{KV: KV, NS: e.ns, DB: e.db, TK: ast.Name.VA} - _, err = e.tx.ClrP(ctx, tkey.Encode(), 0) - - case sql.SCOPE: - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - // Remove the token definition - tkey := &keys.ST{KV: KV, NS: e.ns, DB: e.db, SC: ast.What.VA, TK: ast.Name.VA} - _, err = e.tx.ClrP(ctx, tkey.Encode(), 0) - - } - - return - -} - -func (e *executor) executeRemoveScope(ctx context.Context, ast *sql.RemoveScopeStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - // Remove the scope definition - skey := &keys.SC{KV: KV, NS: e.ns, DB: e.db, SC: ast.Name.VA} - _, err = e.tx.ClrP(ctx, skey.Encode(), 0) - - return - -} - -func (e *executor) executeRemoveEvent(ctx context.Context, ast *sql.RemoveEventStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.DelEV(e.ns, e.db, TB.TB, ast.Name.VA) - - // Remove the event definition - ekey := &keys.EV{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, EV: ast.Name.VA} - if _, err = e.tx.ClrP(ctx, ekey.Encode(), 0); err != nil { - return nil, err - } - - } - - return - -} - -func (e *executor) executeRemoveField(ctx context.Context, ast *sql.RemoveFieldStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.DelFD(e.ns, e.db, TB.TB, ast.Name.VA) - - // Remove the field definition - fkey := &keys.FD{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, FD: ast.Name.VA} - if _, err = e.tx.ClrP(ctx, fkey.Encode(), 0); err != nil { - return nil, err - } - - } - - return - -} - -func (e *executor) executeRemoveIndex(ctx context.Context, ast *sql.RemoveIndexStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.DelIX(e.ns, e.db, TB.TB, ast.Name.VA) - - // Remove the index definition - ikey := &keys.IX{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, IX: ast.Name.VA} - if _, err = e.tx.ClrP(ctx, ikey.Encode(), 0); err != nil { - return nil, err - } - - // Remove the index resource data - dkey := &keys.Index{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB, IX: ast.Name.VA, FD: keys.Ignore} - if _, err = e.tx.ClrP(ctx, dkey.Encode(), 0); err != nil { - return nil, err - } - - } - - return - -} - -func (e *executor) executeRemoveTable(ctx context.Context, ast *sql.RemoveTableStatement) (out []interface{}, err error) { - - if err := e.access(ctx, cnf.AuthDB); err != nil { - return nil, err - } - - for _, TB := range ast.What { - - e.tx.DelTB(e.ns, e.db, TB.TB) - - tb, err := e.tx.GetTB(ctx, e.ns, e.db, TB.TB) - if err != nil { - return nil, err - } - - // Remove the table definition - tkey := &keys.TB{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB} - _, err = e.tx.Clr(ctx, tkey.Encode()) - if err != nil { - return nil, err - } - - // Remove the table resource data - dkey := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: TB.TB} - _, err = e.tx.ClrP(ctx, dkey.Encode(), 0) - if err != nil { - return nil, err - } - - if tb.Lock { - - for _, FT := range tb.From { - - // Remove the foreign table definition - tkey := &keys.FT{KV: KV, NS: e.ns, DB: e.db, TB: FT.TB, FT: TB.TB} - if _, err = e.tx.ClrP(ctx, tkey.Encode(), 0); err != nil { - return nil, err - } - - } - - } - - } - - return - -} diff --git a/db/remove_test.go b/db/remove_test.go deleted file mode 100644 index cdcfd315..00000000 --- a/db/remove_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestRemove(t *testing.T) { - - Convey("Remove a namespace", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE |person:10|; - REMOVE NAMESPACE test; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 0) - - }) - - Convey("Remove a database", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE |person:10|; - REMOVE DATABASE test; - INFO FOR NAMESPACE; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("database").Data(), ShouldHaveLength, 0) - So(res[4].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 0) - - }) - - Convey("Remove a table", t, func() { - - setupDB(workerCount) - - txt := ` - USE NS test DB test; - CREATE |person:10|; - REMOVE TABLE person; - INFO FOR DATABASE; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("table").Data(), ShouldHaveLength, 0) - So(res[4].Status, ShouldEqual, "OK") - So(res[4].Result, ShouldHaveLength, 0) - - }) - -} diff --git a/db/return.go b/db/return.go deleted file mode 100644 index 029c6546..00000000 --- a/db/return.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" -) - -func (e *executor) executeReturn(ctx context.Context, stm *sql.ReturnStatement) (out []interface{}, err error) { - - for _, w := range stm.What { - - switch what := w.(type) { - case *sql.Void: - // Ignore - case *sql.Empty: - // Ignore - default: - val, err := e.fetch(ctx, what, nil) - if err != nil { - return nil, err - } - out = append(out, val) - } - - } - - return - -} diff --git a/db/return_test.go b/db/return_test.go deleted file mode 100644 index 6c7b48d1..00000000 --- a/db/return_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestReturn(t *testing.T) { - - Convey("Return a string", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - RETURN "test"; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldResemble, []interface{}{"test"}) - - }) - - Convey("Return a number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - RETURN 33693; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldResemble, []interface{}{33693.0}) - - }) - - Convey("Return a VOID expression", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - RETURN VOID; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldResemble, []interface{}{}) - - }) - - Convey("Return an EMPTY expression", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - RETURN EMPTY; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldResemble, []interface{}{}) - - }) - -} diff --git a/db/run.go b/db/run.go deleted file mode 100644 index 4ea21b38..00000000 --- a/db/run.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" -) - -func (e *executor) executeRun(ctx context.Context, stm *sql.RunStatement) (out []interface{}, err error) { - - val, err := e.fetch(ctx, stm, nil) - if err != nil { - return nil, err - } - - switch val := val.(type) { - case []interface{}: - out = val - case interface{}: - out = append(out, val) - } - - return - -} diff --git a/db/run_test.go b/db/run_test.go deleted file mode 100644 index 5de9e615..00000000 --- a/db/run_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - "sync" - "testing" - "time" - - "net/http" - "net/http/httptest" - - . "github.com/smartystreets/goconvey/convey" -) - -type Handler struct { - sync.Mutex - count int -} - -func (s *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.Lock() - defer s.Unlock() - s.count++ - fmt.Fprintf(w, "SERVER OK: %d", s.count) -} - -func TestRun(t *testing.T) { - - handler := &Handler{} - server := httptest.NewServer(handler) - defer server.Close() - - Convey("Run statement which runs http requests", t, func() { - - setupDB(1) - - func() { - - txt := ` - USE NS test DB test; - DEFINE TABLE test PERMISSIONS FULL; - DEFINE TABLE temp PERMISSIONS FOR SELECT FULL; - DEFINE EVENT done ON test WHEN true THEN ( - CREATE temp:main; - RUN http.get("` + server.URL + `"); - RUN http.put("` + server.URL + `"); - RUN http.post("` + server.URL + `"); - RUN http.delete("` + server.URL + `"); - RUN http.async.get("` + server.URL + `"); - RUN http.async.put("` + server.URL + `"); - RUN http.async.post("` + server.URL + `"); - RUN http.async.delete("` + server.URL + `"); - ); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[2].Status, ShouldEqual, "OK") - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM test, temp; - CREATE test:main; - SELECT * FROM test, temp; - ` - - res, err := Execute(permsSC(), txt, nil) - time.Sleep(1 * time.Second) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Status, ShouldEqual, "OK") - So(res[1].Result, ShouldHaveLength, 0) - So(res[2].Status, ShouldEqual, "OK") - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Status, ShouldEqual, "OK") - So(res[3].Result, ShouldHaveLength, 2) - - handler.Lock() - So(handler.count, ShouldEqual, 8) - handler.Unlock() - - }() - - }) - -} diff --git a/db/scope_test.go b/db/scope_test.go deleted file mode 100644 index 1b65cd44..00000000 --- a/db/scope_test.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestScope(t *testing.T) { - - Convey("Select records from an array of strings", t, func() { - - setupDB(1) - - func() { - - txt := ` - USE NS test DB test; - DEFINE NAMESPACE test; - DEFINE DATABASE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM [ - "one", - "two", - "tre", - ]; - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, "one") - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, "two") - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, "tre") - - }() - - }) - - Convey("Select records from an array of objects with an id key", t, func() { - - setupDB(1) - - func() { - - txt := ` - USE NS test DB test; - DEFINE NAMESPACE test; - DEFINE DATABASE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM [ - { id: "one" }, - { id: "two" }, - { id: "tre" }, - ]; - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, map[string]interface{}{"id": "one"}) - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, map[string]interface{}{"id": "two"}) - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, map[string]interface{}{"id": "tre"}) - - }() - - }) - - Convey("Select records from an array of objects with no id key", t, func() { - - setupDB(1) - - func() { - - txt := ` - USE NS test DB test; - DEFINE NAMESPACE test; - DEFINE DATABASE test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM [ - { test: "one" }, - { test: "two" }, - { test: "tre" }, - ]; - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, map[string]interface{}{"test": "one"}) - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, map[string]interface{}{"test": "two"}) - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, map[string]interface{}{"test": "tre"}) - - }() - - }) - - Convey("Select records from an array of virtual record things with no permissions", t, func() { - - setupDB(1) - - func() { - - txt := ` - USE NS test DB test; - DEFINE NAMESPACE test; - DEFINE DATABASE test; - CREATE test:one, test:two, test:tre; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM array( - thing("test", "one"), - thing("test", "two"), - thing("test", "tre") - ); - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 0) - - }() - - }) - - Convey("Select records from an array of virtual record things with full permissions", t, func() { - - setupDB(1) - - func() { - - txt := ` - USE NS test DB test; - DEFINE NAMESPACE test; - DEFINE DATABASE test; - DEFINE TABLE test PERMISSIONS FULL; - CREATE test:one, test:two, test:tre; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - - }() - - func() { - - txt := ` - USE NS test DB test; - SELECT * FROM array( - thing("test", "one"), - thing("test", "two"), - thing("test", "tre") - ); - ` - - res, err := Execute(permsSC(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, map[string]interface{}{ - "id": sql.NewThing("test", "one"), - "meta": map[string]interface{}{ - "tb": "test", - "id": "one", - }, - }) - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, map[string]interface{}{ - "id": sql.NewThing("test", "two"), - "meta": map[string]interface{}{ - "tb": "test", - "id": "two", - }, - }) - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, map[string]interface{}{ - "id": sql.NewThing("test", "tre"), - "meta": map[string]interface{}{ - "tb": "test", - "id": "tre", - }, - }) - - }() - - }) - -} diff --git a/db/select.go b/db/select.go deleted file mode 100644 index e441704f..00000000 --- a/db/select.go +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeSelect(ctx context.Context, stm *sql.SelectStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - ctx = context.WithValue(ctx, ctxKeyVersion, stm.Version) - - var what sql.Exprs - - for _, val := range stm.What { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - what = append(what, w) - } - - i := newIterator(e, ctx, stm, false) - - for _, w := range what { - - switch what := w.(type) { - - default: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processQuery(ctx, key, []interface{}{what}) - - case *sql.Table: - key := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: what.TB} - i.processTable(ctx, key) - - case *sql.Ident: - key := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: what.VA} - i.processTable(ctx, key) - - case *sql.Thing: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: what.ID} - i.processThing(ctx, key) - - case *sql.Model: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processModel(ctx, key, what) - - case *sql.Batch: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processBatch(ctx, key, what) - - // Result of subquery - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processQuery(ctx, key, what) - - // Result of subquery with LIMIT 1 - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processQuery(ctx, key, []interface{}{what}) - - } - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchSelect(ctx context.Context, stm *sql.SelectStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeSelect(ctx, stm) - if err != nil { - return nil, err - } - - cnt, err := e.fetchOutputs(ctx, stm) - if err != nil { - return nil, err - } - - switch cnt { - case 1: - switch len(stm.Expr) { - case 1: - f := stm.Expr[0] - switch f.Expr.(type) { - default: - return data.Consume(out).Get(docKeyOne, f.Field).Data(), nil - case *sql.All: - return data.Consume(out).Get(docKeyOne).Data(), nil - } - default: - return data.Consume(out).Get(docKeyOne).Data(), nil - } - default: - switch len(stm.Expr) { - case 1: - f := stm.Expr[0] - switch f.Expr.(type) { - default: - return data.Consume(out).Get(docKeyAll, f.Field).Data(), nil - case *sql.All: - return data.Consume(out).Get(docKeyAll).Data(), nil - } - default: - return data.Consume(out).Get(docKeyAll).Data(), nil - } - } - - return out, err - -} - -func (d *document) runSelect(ctx context.Context, stm *sql.SelectStatement) (interface{}, error) { - - var ok bool - var err error - var met = _SELECT - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.doc == nil && !d.val.Exi() { - return nil, nil - } - - if ok, err = d.check(ctx, stm.Cond); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - return d.yield(ctx, stm, sql.ILLEGAL) - -} diff --git a/db/select_test.go b/db/select_test.go deleted file mode 100644 index 9525db75..00000000 --- a/db/select_test.go +++ /dev/null @@ -1,2167 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestSelect(t *testing.T) { - - Convey("Select records from one thing", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1; - CREATE person:test; - SELECT * FROM person:1; - SELECT * FROM person:test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - - }) - - Convey("Select records from one thing using quotes", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1; - CREATE person:test; - SELECT * FROM person:⟨1⟩; - SELECT * FROM person:⟨test⟩; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - - }) - - Convey("Select records from one table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - CREATE |person:10|; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 11) - - }) - - Convey("Select records from multiple tables", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - CREATE entity:test; - SELECT * FROM person, entity; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 2) - - }) - - Convey("Select records from multiple things and tables", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - CREATE entity:test; - CREATE |person:10|; - CREATE |entity:10|; - SELECT * FROM person:test, entity:test, person, entity; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 10) - So(res[4].Result, ShouldHaveLength, 10) - So(res[5].Result, ShouldHaveLength, 24) - - }) - - Convey("Select records from an array of strings", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - SELECT * FROM ["one", "two", "tre"]; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, "one") - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, "two") - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, "tre") - - }) - - Convey("Select records from an array of objects with an id key", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - SELECT * FROM [{ id: "one" }, { id: "two" }, { id: "tre" }]; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, map[string]interface{}{"id": "one"}) - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, map[string]interface{}{"id": "two"}) - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, map[string]interface{}{"id": "tre"}) - - }) - - Convey("Select records from an array of objects with no id key", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - SELECT * FROM [{ test: "one" }, { test: "two" }, { test: "tre" }]; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, map[string]interface{}{"test": "one"}) - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, map[string]interface{}{"test": "two"}) - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, map[string]interface{}{"test": "tre"}) - - }) - - Convey("Select records from an array of virtual record things", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE test:one, test:two, test:tre; - SELECT * FROM array( - thing("test", "one"), - thing("test", "two"), - thing("test", "tre") - ); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Data(), ShouldResemble, map[string]interface{}{ - "id": sql.NewThing("test", "one"), - "meta": map[string]interface{}{ - "tb": "test", - "id": "one", - }, - }) - So(data.Consume(res[1].Result[1]).Data(), ShouldResemble, map[string]interface{}{ - "id": sql.NewThing("test", "two"), - "meta": map[string]interface{}{ - "tb": "test", - "id": "two", - }, - }) - So(data.Consume(res[1].Result[2]).Data(), ShouldResemble, map[string]interface{}{ - "id": sql.NewThing("test", "tre"), - "meta": map[string]interface{}{ - "tb": "test", - "id": "tre", - }, - }) - - }) - - Convey("Select records with an embedded record field", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:a SET name="Tobias"; - CREATE person:b SET name="Silvana"; - CREATE person:c SET name="Jonathan", father=person:a, mother=person:b; - SELECT meta, name, father, mother FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[4].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[4].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[4].Result[2]).Get("father").Data(), ShouldResemble, &sql.Thing{"person", "a"}) - So(data.Consume(res[4].Result[2]).Get("mother").Data(), ShouldResemble, &sql.Thing{"person", "b"}) - - }) - - Convey("Select '*' parameter from an embedded record field fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:a SET name="Tobias"; - CREATE person:b SET name="Silvana"; - CREATE person:c SET name="Jonathan", father=person:a, mother=person:b; - SELECT meta, name, father.* AS father, mother.* AS mother FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[4].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[4].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[4].Result[2]).Get("father").Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "a"}, - "meta": map[string]interface{}{ - "id": "a", - "tb": "person", - }, - "name": "Tobias", - }) - So(data.Consume(res[4].Result[2]).Get("mother").Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "b"}, - "meta": map[string]interface{}{ - "id": "b", - "tb": "person", - }, - "name": "Silvana", - }) - - }) - - Convey("Select 'id' parameter from an embedded record field fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:a SET name="Tobias"; - CREATE person:b SET name="Silvana"; - CREATE person:c SET name="Jonathan", father=person:a, mother=person:b; - SELECT meta, name, father.id AS father, mother.id AS mother FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[4].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[4].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[4].Result[2]).Get("father").Data(), ShouldResemble, &sql.Thing{"person", "a"}) - So(data.Consume(res[4].Result[2]).Get("mother").Data(), ShouldResemble, &sql.Thing{"person", "b"}) - - }) - - Convey("Select 'name' parameter from an embedded record field fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:a SET name="Tobias"; - CREATE person:b SET name="Silvana"; - CREATE person:c SET name="Jonathan", father=person:a, mother=person:b; - SELECT meta, name, father.name AS father, mother.name AS mother FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[4].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[4].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[4].Result[2]).Get("father").Data(), ShouldResemble, "Tobias") - So(data.Consume(res[4].Result[2]).Get("mother").Data(), ShouldResemble, "Silvana") - - }) - - Convey("Select 'id.name' parameter from an embedded record field fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:a SET name="Tobias"; - CREATE person:b SET name="Silvana"; - CREATE person:c SET name="Jonathan", father=person:a, mother=person:b; - SELECT meta, name, father.id.name AS father, mother.id.name AS mother FROM person ORDER BY meta.id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[4].Result[1]).Get("name").Data(), ShouldEqual, "Silvana") - So(data.Consume(res[4].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[4].Result[2]).Get("father").Data(), ShouldResemble, "Tobias") - So(data.Consume(res[4].Result[2]).Get("mother").Data(), ShouldResemble, "Silvana") - - }) - - Convey("Select records using variable for a `table`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE $tb; - SELECT * FROM $tb; - ` - - res, err := Execute(permsKV(), txt, map[string]interface{}{ - "tb": sql.NewTable("person"), - }) - - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(data.Consume(res[1].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - - }) - - Convey("Select records using variable for a `thing`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE $id; - SELECT * FROM $id; - ` - - res, err := Execute(permsKV(), txt, map[string]interface{}{ - "id": sql.NewThing("person", "test"), - }) - - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 4) - So(data.Consume(res[1].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - - }) - - Convey("Select records using an * subquery", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT * FROM person ORDER BY name); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 5) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[6].Result[4]).Get("name").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select records using an * subquery, with a limit of 1", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT * FROM person ORDER BY name LIMIT 1); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Select records using an * subquery, specifying a single record", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT * FROM person:5); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Select records using an id subquery", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT id FROM (SELECT * FROM person ORDER BY name)); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 5) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[6].Result[4]).Get("name").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select records using an id subquery, with a limit of 1", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT id FROM (SELECT * FROM person ORDER BY name) LIMIT 1); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Select records using an id subquery, specifying a single record", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT id FROM (SELECT * FROM person:5)); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Select records using a single field subquery", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT name FROM person ORDER BY name); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 5) - So(res[6].Result[0], ShouldEqual, "Alexander") - So(res[6].Result[4], ShouldEqual, "Tobias") - - }) - - Convey("Select records using a single field subquery, with a limit of 1", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM (SELECT name FROM person ORDER BY name LIMIT 1); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(res[6].Result[0], ShouldEqual, "Alexander") - - }) - - Convey("Select $thing from a direct `thing` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, person:test AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldResemble, &sql.Thing{"person", "test"}) - - }) - - Convey("Select '*' from a direct `thing` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, person:test.* AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "id": "test", - "tb": "person", - }, - "name": "Tobias", - }) - - }) - - Convey("Select 'id' parameter from a direct `thing` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, person:test.id AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldResemble, &sql.Thing{"person", "test"}) - - }) - - Convey("Select 'name' parameter from a direct `thing` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, person:test.name AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select 'id.name' parameter from a direct `thing` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, person:test.id.name AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select 'id.id.id.name' parameter from a direct `thing` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, person:test.id.id.id.name AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select $param parameter from a direct `param` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET person = person:test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, $person AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldResemble, &sql.Thing{"person", "test"}) - - }) - - Convey("Select '*' parameter from a direct `param` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET person = person:test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, $person.* AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "id": "test", - "tb": "person", - }, - "name": "Tobias", - }) - - }) - - Convey("Select 'id' parameter from a direct `param` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET person = person:test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, $person.id AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldResemble, &sql.Thing{"person", "test"}) - - }) - - Convey("Select 'name' parameter from a direct `param` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET person = person:test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, $person.name AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select 'id.name' parameter from a direct `param` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET person = person:test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, $person.id.name AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select 'id.id.id.name' parameter from a direct `param` record fetch", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET person = person:test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, $person.id.id.id.name AS test FROM tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select $parent parameter from a subquery `param`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, (SELECT $parent FROM tester LIMIT 1) AS test FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldResemble, map[string]interface{}{ - "id": &sql.Thing{"person", "test"}, - "meta": map[string]interface{}{ - "id": "test", - "tb": "person", - }, - "name": "Tobias", - }) - - }) - - Convey("Select 'id' parameter from a subquery `param`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, (SELECT $parent.id FROM tester LIMIT 1) AS test FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldResemble, &sql.Thing{"person", "test"}) - - }) - - Convey("Select 'name' parameter from a subquery `param`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, (SELECT $parent.name FROM tester LIMIT 1) AS test FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select 'id.name' parameter from a subquery `param`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, (SELECT $parent.id.name FROM tester LIMIT 1) AS test FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Select 'id.id.id.name' parameter from a subquery `param`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE tester:test; - CREATE person:test SET name="Tobias"; - SELECT *, (SELECT $parent.id.id.id.name FROM tester LIMIT 1) AS test FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[3].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Filter using VOID to find records where the field is not set", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1; - CREATE person:2 SET test = null; - CREATE person:3 SET test = true; - CREATE person:4 SET test = "Test"; - CREATE person:5 SET test = "1000"; - SELECT test FROM person WHERE test IS VOID; - SELECT test FROM person WHERE test IS NOT VOID; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[6].Result, ShouldHaveLength, 1) - So(res[7].Result, ShouldHaveLength, 4) - - }) - - Convey("Filter using NULL to find records where the field is `null`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1; - CREATE person:2 SET test = null; - CREATE person:3 SET test = true; - CREATE person:4 SET test = "Test"; - CREATE person:5 SET test = "1000"; - SELECT test FROM person WHERE test IS NULL; - SELECT test FROM person WHERE test IS NOT NULL; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[6].Result, ShouldHaveLength, 1) - So(res[7].Result, ShouldHaveLength, 4) - - }) - - Convey("Filter using EMPTY to find records where the field is not set or `null`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1; - CREATE person:2 SET test = null; - CREATE person:3 SET test = true; - CREATE person:4 SET test = "Test"; - CREATE person:5 SET test = "1000"; - SELECT test FROM person WHERE test IS EMPTY; - SELECT test FROM person WHERE test IS NOT EMPTY; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[6].Result, ShouldHaveLength, 2) - So(res[7].Result, ShouldHaveLength, 3) - - }) - - Convey("Filter using boolean logic to find records", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test = "one"; - CREATE person:2 SET test = "two"; - CREATE person:3 SET test = "tre"; - - SELECT test FROM person WHERE test = "one"; - - SELECT test FROM person WHERE test = "one" OR test = "two"; - SELECT test FROM person WHERE test = "one" OR test = "two" OR test = "tre"; - SELECT test FROM person WHERE test = "one" OR (test = "two" OR test = "tre"); - SELECT test FROM person WHERE (test = "one") OR (test = "two") OR (test = "tre"); - SELECT test FROM person WHERE (test = "one") OR ( (test = "two") OR (test = "tre") ); - SELECT test FROM person WHERE ( (test = "one") OR (test = "two") OR (test = "tre") ); - - SELECT test FROM person WHERE test = "one" AND test = "two" AND test = "tre"; - SELECT test FROM person WHERE test = "one" AND test != "two" AND test != "tre"; - SELECT test FROM person WHERE test = "one" AND (test != "two" AND test != "tre"); - SELECT test FROM person WHERE (test = "one") AND (test != "two") AND (test != "tre"); - SELECT test FROM person WHERE (test = "one") AND ( (test != "two") AND (test != "tre") ); - SELECT test FROM person WHERE ( (test = "one") AND (test != "two") AND (test != "tre") ); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 17) - - So(res[4].Result, ShouldHaveLength, 1) - - So(res[5].Result, ShouldHaveLength, 2) - So(res[6].Result, ShouldHaveLength, 3) - So(res[7].Result, ShouldHaveLength, 3) - So(res[8].Result, ShouldHaveLength, 3) - So(res[9].Result, ShouldHaveLength, 3) - So(res[10].Result, ShouldHaveLength, 3) - - So(res[11].Result, ShouldHaveLength, 0) - So(res[12].Result, ShouldHaveLength, 1) - So(res[13].Result, ShouldHaveLength, 1) - So(res[14].Result, ShouldHaveLength, 1) - So(res[15].Result, ShouldHaveLength, 1) - So(res[16].Result, ShouldHaveLength, 1) - - }) - - Convey("Filter records using an id subquery", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM person WHERE id IN (SELECT id FROM person); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 5) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[6].Result[4]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Filter records using an id subquery, with a limit of 1", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM person WHERE id = (SELECT id FROM person LIMIT 1); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Filter records using an single field subquery", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM person WHERE name IN (SELECT name FROM person ORDER BY name); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 5) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Tobias") - So(data.Consume(res[6].Result[4]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Filter records using a single field subquery, with a limit of 1", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET name="Tobias"; - CREATE person:2 SET name="Silvana"; - CREATE person:3 SET name="Jonathan"; - CREATE person:4 SET name="Benjamin"; - CREATE person:5 SET name="Alexander"; - SELECT * FROM person WHERE name = (SELECT name FROM person ORDER BY name LIMIT 1); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("name").Data(), ShouldEqual, "Alexander") - - }) - - Convey("Filter records using a single field subquery, with a limit of 1", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET age=30; - CREATE person:1 SET name="Tobias", age=30; - CREATE person:2 SET name="Silvana", age=27; - CREATE person:3 SET name="Jonathan", age=32; - CREATE person:4 SET name="Benjamin", age=31; - CREATE person:5 SET name="Alexander", age=22; - SELECT * FROM person WHERE age >= person:⟨1⟩.age ORDER BY name; - SELECT * FROM person WHERE age >= person:test.age ORDER BY name; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 9) - So(res[7].Result, ShouldHaveLength, 4) - So(data.Consume(res[7].Result[0]).Get("name").Data(), ShouldEqual, nil) - So(data.Consume(res[7].Result[1]).Get("name").Data(), ShouldEqual, "Benjamin") - So(data.Consume(res[7].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[7].Result[3]).Get("name").Data(), ShouldEqual, "Tobias") - So(res[8].Result, ShouldHaveLength, 4) - So(data.Consume(res[8].Result[0]).Get("name").Data(), ShouldEqual, nil) - So(data.Consume(res[8].Result[1]).Get("name").Data(), ShouldEqual, "Benjamin") - So(data.Consume(res[8].Result[2]).Get("name").Data(), ShouldEqual, "Jonathan") - So(data.Consume(res[8].Result[3]).Get("name").Data(), ShouldEqual, "Tobias") - - }) - - Convey("Group records by field", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:1 SET test = true; - UPDATE person:2 SET test = false; - UPDATE person:3 SET test = false; - UPDATE person:4 SET test = true; - UPDATE person:5 SET test = nil; - SELECT test FROM person GROUP BY test ORDER BY test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[7].Result, ShouldHaveLength, 3) - So(data.Consume(res[7].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[7].Result[1]).Get("test").Data(), ShouldEqual, false) - So(data.Consume(res[7].Result[2]).Get("test").Data(), ShouldEqual, true) - - }) - - Convey("Group and count records by field", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..5|; - UPDATE person:1 SET test = true; - UPDATE person:2 SET test = false; - UPDATE person:3 SET test = false; - UPDATE person:4 SET test = true; - UPDATE person:5 SET test = nil; - SELECT test, count(*) AS total FROM person GROUP BY test ORDER BY test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[7].Result, ShouldHaveLength, 3) - So(data.Consume(res[7].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[7].Result[0]).Get("total").Data(), ShouldEqual, 1) - So(data.Consume(res[7].Result[1]).Get("test").Data(), ShouldEqual, false) - So(data.Consume(res[7].Result[1]).Get("total").Data(), ShouldEqual, 2) - So(data.Consume(res[7].Result[2]).Get("test").Data(), ShouldEqual, true) - So(data.Consume(res[7].Result[2]).Get("total").Data(), ShouldEqual, 2) - - }) - - Convey("Group and count records by field with alias", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..5|; - UPDATE person:1 SET test = "something"; - UPDATE person:2 SET test = "nothing"; - UPDATE person:3 SET test = "nothing"; - UPDATE person:4 SET test = "something"; - UPDATE person:5 SET test = nil; - SELECT string.length(test) AS test, count(*) AS total FROM person GROUP BY test ORDER BY test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[7].Result, ShouldHaveLength, 3) - So(data.Consume(res[7].Result[0]).Get("test").Data(), ShouldEqual, 0) - So(data.Consume(res[7].Result[0]).Get("total").Data(), ShouldEqual, 1) - So(data.Consume(res[7].Result[1]).Get("test").Data(), ShouldEqual, 7) - So(data.Consume(res[7].Result[1]).Get("total").Data(), ShouldEqual, 2) - So(data.Consume(res[7].Result[2]).Get("test").Data(), ShouldEqual, 9) - So(data.Consume(res[7].Result[2]).Get("total").Data(), ShouldEqual, 2) - - }) - - Convey("Group and retrieve distinct records by field", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..5|; - UPDATE person:1 SET test = "Hello"; - UPDATE person:2 SET test = "World"; - UPDATE person:3 SET test = "World"; - UPDATE person:4 SET test = "Hello"; - UPDATE person:5 SET test = "Hello"; - SELECT test, distinct(id) AS docs FROM person GROUP BY test ORDER BY test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 8) - So(res[7].Result, ShouldHaveLength, 2) - So(data.Consume(res[7].Result[0]).Get("test").Data(), ShouldEqual, "Hello") - So(data.Consume(res[7].Result[0]).Get("docs").Data(), ShouldContain, sql.NewThing("person", 1)) - So(data.Consume(res[7].Result[0]).Get("docs").Data(), ShouldContain, sql.NewThing("person", 4)) - So(data.Consume(res[7].Result[0]).Get("docs").Data(), ShouldContain, sql.NewThing("person", 5)) - So(data.Consume(res[7].Result[1]).Get("test").Data(), ShouldEqual, "World") - So(data.Consume(res[7].Result[1]).Get("docs").Data(), ShouldContain, sql.NewThing("person", 2)) - So(data.Consume(res[7].Result[1]).Get("docs").Data(), ShouldContain, sql.NewThing("person", 3)) - - }) - - Convey("Group and retrieve more than 10000 records to test incremental processing", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10000|; - SELECT meta.tb, count(*) AS test FROM person GROUP BY meta.tb; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10000) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, 10000) - - }) - - Convey("Order records ascending", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test ASC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, "Tobie") - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, "ändrew") - - }) - - Convey("Order records descending", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test DESC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, "ändrew") - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, "Tobie") - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, nil) - - }) - - Convey("Order records with collation", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test COLLATE ASC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, "ändrew") - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, "Tobie") - - }) - - Convey("Order records with en-GB collation", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test COLLATE 'en-GB' ASC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, "ändrew") - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, "Tobie") - - }) - - Convey("Order records with collation and numeric sorting", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test COLLATE NUMERIC ASC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, "ändrew") - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, "Tobie") - - }) - - Convey("Order records with en-GB collation and numeric sorting", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test COLLATE 'en-GB' NUMERIC ASC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, "ändrew") - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, "Tobie") - - }) - - Convey("Order records with en-GB collation and numeric and insensitive sorting using unicode definition", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - UPDATE person:3 SET test = "ändrew"; - UPDATE person:5 SET test = "Another"; - UPDATE person:7 SET test = "alexander"; - UPDATE person:9 SET test = "Alexander"; - UPDATE person:2 SET test = "Tobie"; - UPDATE person:4 SET test = "1000"; - UPDATE person:6 SET test = "2"; - UPDATE person:8 SET test = null; - SELECT test FROM person ORDER BY test COLLATE 'en-GB-u-kn-true-kc-false' ASC; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 11) - So(res[10].Result, ShouldHaveLength, 10) - So(data.Consume(res[10].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[10].Result[3]).Get("test").Data(), ShouldEqual, "2") - So(data.Consume(res[10].Result[4]).Get("test").Data(), ShouldEqual, "1000") - So(data.Consume(res[10].Result[5]).Get("test").Data(), ShouldEqual, "Alexander") - So(data.Consume(res[10].Result[6]).Get("test").Data(), ShouldEqual, "alexander") - So(data.Consume(res[10].Result[7]).Get("test").Data(), ShouldEqual, "ändrew") - So(data.Consume(res[10].Result[8]).Get("test").Data(), ShouldEqual, "Another") - So(data.Consume(res[10].Result[9]).Get("test").Data(), ShouldEqual, "Tobie") - - }) - - Convey("Order records from multiple tables", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test; - CREATE entity:test; - SELECT * FROM person, entity ORDER BY id; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 2) - So(data.Consume(res[3].Result[0]).Get("meta.tb").Data(), ShouldEqual, "entity") - So(data.Consume(res[3].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person") - - }) - - Convey("Limit records using a number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY 5; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 5) - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[2].Result[4]).Get("meta.id").Data(), ShouldEqual, 5) - - }) - - Convey("Limit records using a parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET count = 5; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY $count; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 5) - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[3].Result[4]).Get("meta.id").Data(), ShouldEqual, 5) - - }) - - Convey("Limit records using an invalid parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET count = "test"; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY $count; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 0) - So(res[3].Status, ShouldEqual, "ERR") - So(res[3].Detail, ShouldEqual, "Found 'test' but LIMIT expression must be a number") - - }) - - Convey("Limit records using a negative number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY -10; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - - }) - - Convey("Limit records using a minimum number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY 0; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 0) - - }) - - Convey("Limit records using a maximum number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY 100; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - - }) - - Convey("Limit records using a number and start records at a number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY 5 START AT 5; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 5) - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 6) - So(data.Consume(res[2].Result[4]).Get("meta.id").Data(), ShouldEqual, 10) - - }) - - Convey("Start records using a number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person START AT 5; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 5) - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 6) - So(data.Consume(res[2].Result[4]).Get("meta.id").Data(), ShouldEqual, 10) - - }) - - Convey("Start records using a parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET count = 5; - CREATE |person:1..10|; - SELECT * FROM person START AT $count; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 5) - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 6) - So(data.Consume(res[3].Result[4]).Get("meta.id").Data(), ShouldEqual, 10) - - }) - - Convey("Start records using an invalid parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET count = "test"; - CREATE |person:1..10|; - SELECT * FROM person START AT $count; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 0) - So(res[3].Status, ShouldEqual, "ERR") - So(res[3].Detail, ShouldEqual, "Found 'test' but START expression must be a number") - - }) - - Convey("Start records using a negative number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person START AT -10; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - - }) - - Convey("Start records using a lower minimum number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person START AT 0; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 10) - - }) - - Convey("Start records using a greater maximum number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person START AT 100; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 0) - - }) - - Convey("Start records using a number and limit records by a number", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE |person:1..10|; - SELECT * FROM person LIMIT BY 5 START AT 5; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 10) - So(res[2].Result, ShouldHaveLength, 5) - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 6) - So(data.Consume(res[2].Result[4]).Get("meta.id").Data(), ShouldEqual, 10) - - }) - - Convey("Fetch records using a fetchplan to fetch remote records easily", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET - one=tester:test, - mult=[], - mult+=temper:one, - mult+=temper:two, - mult+=temper:tre - ; - CREATE tester:test SET tags=["some","tags"]; - CREATE temper:one SET tester=tester:test; - CREATE temper:two SET tester=tester:test; - CREATE temper:tre SET tester=tester:test; - SELECT * FROM person:test FETCH one, mult, mult.*.tester; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 1) - So(data.Consume(res[6].Result[0]).Get("meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[6].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[6].Result[0]).Get("one.meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[6].Result[0]).Get("one.meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[6].Result[0]).Get("one.tags").Data(), ShouldResemble, []interface{}{"some", "tags"}) - So(data.Consume(res[6].Result[0]).Get("mult[0].meta.id").Data(), ShouldEqual, "one") - So(data.Consume(res[6].Result[0]).Get("mult[0].meta.tb").Data(), ShouldEqual, "temper") - So(data.Consume(res[6].Result[0]).Get("mult[0].tester.meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[6].Result[0]).Get("mult[0].tester.meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[6].Result[0]).Get("mult[0].tester.tags").Data(), ShouldResemble, []interface{}{"some", "tags"}) - So(data.Consume(res[6].Result[0]).Get("mult[1].meta.id").Data(), ShouldEqual, "two") - So(data.Consume(res[6].Result[0]).Get("mult[1].meta.tb").Data(), ShouldEqual, "temper") - So(data.Consume(res[6].Result[0]).Get("mult[1].tester.meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[6].Result[0]).Get("mult[1].tester.meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[6].Result[0]).Get("mult[1].tester.tags").Data(), ShouldResemble, []interface{}{"some", "tags"}) - So(data.Consume(res[6].Result[0]).Get("mult[2].meta.id").Data(), ShouldEqual, "tre") - So(data.Consume(res[6].Result[0]).Get("mult[2].meta.tb").Data(), ShouldEqual, "temper") - So(data.Consume(res[6].Result[0]).Get("mult[2].tester.meta.id").Data(), ShouldEqual, "test") - So(data.Consume(res[6].Result[0]).Get("mult[2].tester.meta.tb").Data(), ShouldEqual, "tester") - So(data.Consume(res[6].Result[0]).Get("mult[2].tester.tags").Data(), ShouldResemble, []interface{}{"some", "tags"}) - - }) - - Convey("Version records using a datetime", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE TABLE person VERSIONED; - CREATE |person:1..10|; - SELECT * FROM person VERSION "2017-01-01"; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 10) - So(res[3].Result, ShouldHaveLength, 0) - So(res[4].Result, ShouldHaveLength, 10) - - }) - - Convey("Version records using a date parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE TABLE person VERSIONED; - LET date = "2017-01-01"; - CREATE |person:1..10|; - SELECT * FROM person VERSION $date; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[3].Result, ShouldHaveLength, 10) - So(res[4].Result, ShouldHaveLength, 0) - So(res[5].Result, ShouldHaveLength, 10) - - }) - - Convey("Version records using a time parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE TABLE person VERSIONED; - LET time = "2017-01-01T15:04:05+07:00"; - CREATE |person:1..10|; - SELECT * FROM person VERSION $time; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[3].Result, ShouldHaveLength, 10) - So(res[4].Result, ShouldHaveLength, 0) - So(res[5].Result, ShouldHaveLength, 10) - - }) - - Convey("Version records using an invalid parameter", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE TABLE person VERSIONED; - LET time = "test"; - CREATE |person:1..10|; - SELECT * FROM person VERSION $time; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[3].Result, ShouldHaveLength, 10) - So(res[4].Result, ShouldHaveLength, 0) - So(res[4].Status, ShouldEqual, "ERR") - So(res[4].Detail, ShouldEqual, "Found 'test' but VERSION expression must be a date or time") - So(res[5].Result, ShouldHaveLength, 10) - - }) - - Convey("Test version on a thing", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE TABLE person VERSIONED; - LET old = time.now(); - CREATE person:test; - UPDATE person:test SET test = 1; - LET one = time.now(); - UPDATE person:test SET test = 2; - LET two = time.now(); - UPDATE person:test SET test = 3; - LET tre = time.now(); - SELECT * FROM person VERSION $old; - SELECT * FROM person VERSION $one; - SELECT * FROM person VERSION $two; - SELECT * FROM person VERSION $tre; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 15) - So(res[4].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 1) - So(res[8].Result, ShouldHaveLength, 1) - So(res[10].Result, ShouldHaveLength, 0) - So(res[11].Result, ShouldHaveLength, 1) - So(data.Consume(res[11].Result[0]).Get("test").Data(), ShouldEqual, 1) - So(res[12].Result, ShouldHaveLength, 1) - So(data.Consume(res[12].Result[0]).Get("test").Data(), ShouldEqual, 2) - So(res[13].Result, ShouldHaveLength, 1) - So(data.Consume(res[13].Result[0]).Get("test").Data(), ShouldEqual, 3) - So(res[14].Result, ShouldHaveLength, 1) - So(data.Consume(res[14].Result[0]).Get("test").Data(), ShouldEqual, 3) - - }) - - Convey("Test version on a table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - DEFINE TABLE person VERSIONED; - LET old = time.now(); - CREATE |person:1..3|; - UPDATE person:1, person:2, person:3 SET test = 1; - LET one = time.now(); - UPDATE person:1, person:2, person:3 SET test = 2; - LET two = time.now(); - UPDATE person:1, person:2, person:3 SET test = 3; - LET tre = time.now(); - SELECT * FROM person VERSION $old; - SELECT * FROM person VERSION $one; - SELECT * FROM person VERSION $two; - SELECT * FROM person VERSION $tre; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 15) - So(res[4].Result, ShouldHaveLength, 3) - So(res[6].Result, ShouldHaveLength, 3) - So(res[8].Result, ShouldHaveLength, 3) - So(res[10].Result, ShouldHaveLength, 0) - So(res[11].Result, ShouldHaveLength, 3) - So(data.Consume(res[11].Result).Get("0.test").Data(), ShouldEqual, 1) - So(data.Consume(res[11].Result).Get("1.test").Data(), ShouldEqual, 1) - So(data.Consume(res[11].Result).Get("2.test").Data(), ShouldEqual, 1) - So(res[12].Result, ShouldHaveLength, 3) - So(data.Consume(res[12].Result).Get("0.test").Data(), ShouldEqual, 2) - So(data.Consume(res[12].Result).Get("1.test").Data(), ShouldEqual, 2) - So(data.Consume(res[12].Result).Get("2.test").Data(), ShouldEqual, 2) - So(res[13].Result, ShouldHaveLength, 3) - So(data.Consume(res[13].Result).Get("0.test").Data(), ShouldEqual, 3) - So(data.Consume(res[13].Result).Get("1.test").Data(), ShouldEqual, 3) - So(data.Consume(res[13].Result).Get("2.test").Data(), ShouldEqual, 3) - So(res[14].Result, ShouldHaveLength, 3) - So(data.Consume(res[14].Result).Get("0.test").Data(), ShouldEqual, 3) - So(data.Consume(res[14].Result).Get("1.test").Data(), ShouldEqual, 3) - So(data.Consume(res[14].Result).Get("2.test").Data(), ShouldEqual, 3) - - }) - -} diff --git a/db/session.go b/db/session.go deleted file mode 100644 index 64fefed0..00000000 --- a/db/session.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "github.com/surrealdb/fibre" -) - -func session(c *fibre.Context) (out map[string]interface{}) { - - out = make(map[string]interface{}) - - out[varKeyIp] = c.IP().String() - - out[varKeyId] = c.Get(varKeyUniq) - - out[varKeyOrigin] = c.Origin() - - return - -} diff --git a/db/socket.go b/db/socket.go deleted file mode 100644 index cba94b36..00000000 --- a/db/socket.go +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - "sync" - - "context" - - "github.com/surrealdb/fibre" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" - "github.com/surrealdb/surrealdb/util/uuid" -) - -type socket struct { - mutex sync.Mutex - fibre *fibre.Context - sends map[string][]interface{} - items map[string][]interface{} - lives map[string]*sql.LiveStatement -} - -func clear(id string) { - go func() { - sockets.Range(func(key, val interface{}) bool { - val.(*socket).clear(id + "-bg") - val.(*socket).clear(id) - return true - }) - }() -} - -func flush(id string) { - go func() { - sockets.Range(func(key, val interface{}) bool { - val.(*socket).flush(id + "-bg") - val.(*socket).flush(id) - return true - }) - }() -} - -func send(id string) { - go func() { - sockets.Range(func(key, val interface{}) bool { - val.(*socket).send(id + "-bg") - val.(*socket).send(id) - return true - }) - }() -} - -// TODO remove this when distributed -// We need to remove this when moving -// to a distributed cluster as -// websockets might be managed by an -// alternative server, and should not -// be removed on node startup. - -func tidy() error { - - ctx := context.Background() - - txn, _ := txn.New(ctx, true) - - defer txn.Commit() - - nss, err := txn.AllNS(ctx) - if err != nil { - return err - } - - for _, ns := range nss { - - dbs, err := txn.AllDB(ctx, ns.Name.VA) - if err != nil { - return err - } - - for _, db := range dbs { - - tbs, err := txn.AllTB(ctx, ns.Name.VA, db.Name.VA) - if err != nil { - return err - } - - for _, tb := range tbs { - - key := &keys.LV{KV: KV, NS: ns.Name.VA, DB: db.Name.VA, TB: tb.Name.VA, LV: keys.Ignore} - if _, err = txn.ClrP(ctx, key.Encode(), 0); err != nil { - return err - } - - } - - } - - } - - return nil - -} - -func (s *socket) ctx() (ctx context.Context) { - - ctx = context.Background() - - auth := s.fibre.Get(ctxKeyAuth).(*cnf.Auth) - sess := s.fibre.Get(ctxKeyVars).(map[string]interface{}) - - vars := data.Consume(sess) - vars.Set(ENV, varKeyEnv) - vars.Set(auth.Data, varKeyAuth) - vars.Set(auth.Scope, varKeyScope) - vars.Set(session(s.fibre), varKeySession) - ctx = context.WithValue(ctx, ctxKeyVars, vars) - ctx = context.WithValue(ctx, ctxKeyKind, auth.Kind) - - return - -} - -func (s *socket) queue(id, query, action string, result interface{}) { - - s.mutex.Lock() - defer s.mutex.Unlock() - - s.items[id] = append(s.items[id], &Dispatch{ - Query: query, - Action: action, - Result: result, - }) - -} - -func (s *socket) clear(id string) (err error) { - - s.mutex.Lock() - defer s.mutex.Unlock() - - delete(s.items, id) - - return - -} - -func (s *socket) flush(id string) (err error) { - - s.mutex.Lock() - defer s.mutex.Unlock() - - s.sends[id] = append(s.sends[id], s.items[id]...) - - delete(s.items, id) - - return - -} - -func (s *socket) send(id string) (err error) { - - s.mutex.Lock() - defer s.mutex.Unlock() - - // If there are no pending message - // notifications for this socket - // then ignore this method call. - - if len(s.sends[id]) == 0 { - return nil - } - - // Create a new rpc notification - // object so that we can send the - // batch changes in one go. - - obj := &fibre.RPCNotification{ - Method: "notify", - Params: s.sends[id], - } - - // Notify the websocket connection - // y sending an RPCNotification type - // to the notify channel. - - s.fibre.Socket().Notify(obj) - - // Make sure that we clear all the - // pending message notifications - // for this socket when done. - - delete(s.sends, id) - - return - -} - -func (s *socket) check(e *executor, ctx context.Context, ns, db, tb string) (err error) { - - var tbv *sql.DefineTableStatement - - // If we are authenticated using DB, NS, - // or KV permissions level, then we can - // ignore all permissions checks. - - if perm(ctx) < cnf.AuthSC { - return nil - } - - // First check that the NS exists, as - // otherwise, the scoped authentication - // request can not do anything. - - _, err = e.tx.GetNS(ctx, ns) - if err != nil { - return err - } - - // Next check that the DB exists, as - // otherwise, the scoped authentication - // request can not do anything. - - _, err = e.tx.GetDB(ctx, ns, db) - if err != nil { - return err - } - - // Then check that the TB exists, as - // otherwise, the scoped authentication - // request can not do anything. - - tbv, err = e.tx.GetTB(ctx, ns, db, tb) - if err != nil { - return err - } - - // If the table has any permissions - // specified, then let's check if this - // query is allowed access to the table. - - switch p := tbv.Perms.(type) { - case *sql.PermExpression: - return e.fetchPerms(ctx, p.Select, tbv.Name) - default: - return &PermsError{table: tb} - } - -} - -func (s *socket) deregister(id string) { - - sockets.Delete(id) - - ctx := context.Background() - - txn, _ := kvs.Begin(ctx, true) - - defer txn.Commit() - - for id, stm := range s.lives { - - for _, w := range stm.What { - - switch what := w.(type) { - - case *sql.Table: - - key := &keys.LV{KV: KV, NS: stm.NS, DB: stm.DB, TB: what.TB, LV: id} - txn.Clr(ctx, key.Encode()) - - case *sql.Ident: - - key := &keys.LV{KV: KV, NS: stm.NS, DB: stm.DB, TB: what.VA, LV: id} - txn.Clr(ctx, key.Encode()) - - } - - } - - } - -} - -func (s *socket) executeLive(e *executor, ctx context.Context, stm *sql.LiveStatement) (out []interface{}, err error) { - - stm.FB = e.id - stm.NS = e.ns - stm.DB = e.db - - s.mutex.Lock() - defer s.mutex.Unlock() - - // Generate a new query uuid. - - stm.ID = uuid.New().String() - - // Store the live query on the socket. - - s.lives[stm.ID] = stm - - // Return the query id to the user. - - out = append(out, stm.ID) - - // Store the live query in the database layer. - - for key, val := range stm.What { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - stm.What[key] = w - } - - for _, w := range stm.What { - - switch what := w.(type) { - - default: - return nil, fmt.Errorf("Can not execute LIVE query using value '%v'", what) - - case *sql.Table: - - key := &keys.LV{KV: KV, NS: stm.NS, DB: stm.DB, TB: what.TB, LV: stm.ID} - if _, err = e.tx.Put(ctx, 0, key.Encode(), stm.Encode()); err != nil { - return nil, err - } - - case *sql.Ident: - - key := &keys.LV{KV: KV, NS: stm.NS, DB: stm.DB, TB: what.VA, LV: stm.ID} - if _, err = e.tx.Put(ctx, 0, key.Encode(), stm.Encode()); err != nil { - return nil, err - } - - } - - } - - return - -} - -func (s *socket) executeKill(e *executor, ctx context.Context, stm *sql.KillStatement) (out []interface{}, err error) { - - s.mutex.Lock() - defer s.mutex.Unlock() - - // Remove the live query from the database layer. - - var what sql.Exprs - - for _, val := range stm.What { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - what = append(what, w) - } - - for _, w := range what { - - switch what := w.(type) { - - default: - return nil, fmt.Errorf("Can not execute KILL query using value '%v'", what) - - case string: - - if qry, ok := s.lives[what]; ok { - - // Delete the live query from the saved queries. - - delete(s.lives, qry.ID) - - // Delete the live query from the database layer. - - for _, w := range qry.What { - - switch what := w.(type) { - - case *sql.Table: - key := &keys.LV{KV: KV, NS: qry.NS, DB: qry.DB, TB: what.TB, LV: qry.ID} - _, err = e.tx.Clr(ctx, key.Encode()) - - case *sql.Ident: - key := &keys.LV{KV: KV, NS: qry.NS, DB: qry.DB, TB: what.VA, LV: qry.ID} - _, err = e.tx.Clr(ctx, key.Encode()) - - } - - } - - } - - } - - } - - return - -} diff --git a/db/table.go b/db/table.go deleted file mode 100644 index 38a00ea2..00000000 --- a/db/table.go +++ /dev/null @@ -1,668 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/fncs" - "github.com/surrealdb/surrealdb/util/keys" -) - -// Table checks if any table views are specified for -// this table, and executes them in name order. -func (d *document) table(ctx context.Context, when method) (err error) { - - if !d.i.e.opts.tables { - return nil - } - - // Check if this query has been run - // in forced mode, because of an - // index or foreign table update. - - forced := d.forced(ctx) - - // If this document has not changed - // then there is no need to update - // any registered foreign tables. - - if !forced && !d.changed { - return nil - } - - // Get the foreign read-only tables - // specified for this table, and - // update values which have changed. - - fts, err := d.i.e.tx.AllFT(ctx, d.key.NS, d.key.DB, d.key.TB) - if err != nil { - return err - } - - for _, ft := range fts { - - var ok bool - var prv *sql.Thing - var doc *sql.Thing - - ok, err = d.check(ctx, ft.Cond) - if err != nil { - return err - } - - if len(ft.Group) > 0 { - - // If there are GROUP BY clauses then - // let's calculate the - - old := make([]interface{}, len(ft.Group)) - now := make([]interface{}, len(ft.Group)) - - for k, e := range ft.Group { - old[k], _ = d.i.e.fetch(ctx, e.Expr, d.initial) - now[k], _ = d.i.e.fetch(ctx, e.Expr, d.current) - } - - prv = sql.NewThing(ft.Name.VA, fmt.Sprintf("%v", old)) - doc = sql.NewThing(ft.Name.VA, fmt.Sprintf("%v", now)) - - } else { - - // Otherwise let's use the id of the - // current record as the basis of the - // new record in the other table. - - doc = sql.NewThing(ft.Name.VA, d.id.ID) - - } - - switch ok { - - // If the document does not match the table - // WHERE condition, then remove it from - // the table, or remove it from the aggregate. - - case false: - - if len(ft.Group) > 0 { - - if !forced && when != _CREATE { - err = d.tableModify(ctx, prv, ft.Expr, _REMOVE) - if err != nil { - return err - } - } - - } else { - - err = d.tableDelete(ctx, doc, ft.Expr) - if err != nil { - return err - } - - } - - // If the document does match the table - // WHERE condition, then add it to the - // table, or add it to the aggregate. - - case true: - - if len(ft.Group) > 0 { - - if !forced && when != _CREATE { - err = d.tableModify(ctx, prv, ft.Expr, _REMOVE) - if err != nil { - return err - } - } - - if when != _DELETE { - err = d.tableModify(ctx, doc, ft.Expr, _CHANGE) - if err != nil { - return err - } - } - - } else { - - err = d.tableUpdate(ctx, doc, ft.Expr) - if err != nil { - return err - } - - } - - } - - } - - return - -} - -func (d *document) tableDelete(ctx context.Context, tng *sql.Thing, exp sql.Fields) (err error) { - - stm := &sql.DeleteStatement{ - What: sql.Exprs{tng}, - } - - key := &keys.Thing{KV: KV, NS: d.i.e.ns, DB: d.i.e.db, TB: tng.TB, ID: tng.ID} - - i := newIterator(d.i.e, ctx, stm, true) - - i.processThing(ctx, key) - - _, err = i.Yield(ctx) - - return err - -} - -func (d *document) tableUpdate(ctx context.Context, tng *sql.Thing, exp sql.Fields) (err error) { - - res, err := d.yield(ctx, &sql.SelectStatement{Expr: exp}, sql.ILLEGAL) - if err != nil { - return err - } - - stm := &sql.UpdateStatement{ - What: sql.Exprs{tng}, - Data: &sql.ContentExpression{Data: res}, - } - - key := &keys.Thing{KV: KV, NS: d.i.e.ns, DB: d.i.e.db, TB: tng.TB, ID: tng.ID} - - i := newIterator(d.i.e, ctx, stm, true) - - i.processThing(ctx, key) - - _, err = i.Yield(ctx) - - return err - -} - -func (d *document) tableModify(ctx context.Context, tng *sql.Thing, exp sql.Fields, when modify) (err error) { - - var doc *data.Doc - - switch when { - case _REMOVE: - doc = d.initial - case _CHANGE: - doc = d.current - } - - set := &sql.DataExpression{} - - for _, e := range exp { - - if f, ok := e.Expr.(*sql.FuncExpression); ok && f.Aggr { - - var v interface{} - - args := make([]interface{}, len(f.Args)) - for x := 0; x < len(f.Args); x++ { - args[x], _ = d.i.e.fetch(ctx, f.Args[x], doc) - } - - // If the function is math.stddev() or - // math.variance(), then we need to work - // out the value as a whole, and not the - // result of each record separately. - - switch f.Name { - default: - v, err = fncs.Run(ctx, f.Name, args...) - case "math.stddev": - v = args[0] - case "math.variance": - v = args[0] - } - - if err != nil { - return err - } - - switch f.Name { - case "distinct": - tableChg(set, e.Field, v, when) - case "count": - tableChg(set, e.Field, v, when) - case "count.if": - tableChg(set, e.Field, v, when) - case "count.not": - tableChg(set, e.Field, v, when) - case "math.sum": - tableChg(set, e.Field, v, when) - case "math.min": - tableMin(set, e.Field, v, when) - case "math.max": - tableMax(set, e.Field, v, when) - case "math.mean": - tableMean(set, e.Field, v, when) - case "math.stddev": - switch a := v.(type) { - case []interface{}: - for _, v := range a { - tableStddev(set, e.Field, v, when) - } - default: - tableStddev(set, e.Field, v, when) - } - case "math.variance": - switch a := v.(type) { - case []interface{}: - for _, v := range a { - tableVariance(set, e.Field, v, when) - } - default: - tableVariance(set, e.Field, v, when) - } - } - - continue - - } - - o, err := d.i.e.fetch(ctx, e.Expr, doc) - if err != nil { - return err - } - - tableSet(set, e.Field, o, when) - - } - - stm := &sql.UpdateStatement{ - What: sql.Exprs{tng}, - Data: set, - } - - key := &keys.Thing{KV: KV, NS: d.i.e.ns, DB: d.i.e.db, TB: tng.TB, ID: tng.ID} - - i := newIterator(d.i.e, ctx, stm, true) - - i.processThing(ctx, key) - - _, err = i.Yield(ctx) - - return err - -} - -func tableSet(set *sql.DataExpression, key string, val interface{}, when modify) { - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: val, - }) - -} - -func tableChg(set *sql.DataExpression, key string, val interface{}, when modify) { - - var op sql.Token - - switch when { - case _REMOVE: - op = sql.DEC - case _CHANGE: - op = sql.INC - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: op, - RHS: val, - }) - -} - -func tableMin(set *sql.DataExpression, key string, val interface{}, when modify) { - - if when == _CHANGE { - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.SubExpression{ - &sql.IfelseStatement{ - Cond: sql.Exprs{ - &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.Empty{}, - }, - Op: sql.OR, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.GT, - RHS: val, - }, - }, - }, - Then: sql.Exprs{ - val, - }, - Else: sql.NewIdent(key), - }, - }, - }) - - } - -} - -func tableMax(set *sql.DataExpression, key string, val interface{}, when modify) { - - if when == _CHANGE { - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.SubExpression{ - &sql.IfelseStatement{ - Cond: sql.Exprs{ - &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.Empty{}, - }, - Op: sql.OR, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.LT, - RHS: val, - }, - }, - }, - Then: sql.Exprs{ - val, - }, - Else: sql.NewIdent(key), - }, - }, - }) - - } - -} - -func tableMean(set *sql.DataExpression, key string, val interface{}, when modify) { - - var op sql.Token - - switch when { - case _REMOVE: - op = sql.DEC - case _CHANGE: - op = sql.INC - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: op, - RHS: 1, - }) - - switch when { - case _REMOVE: - op = sql.SUB - case _CHANGE: - op = sql.ADD - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.BinaryExpression{ - LHS: &sql.SubExpression{ - Expr: &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.MUL, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: sql.SUB, - RHS: 1, - }, - }, - Op: op, - RHS: val, - }, - }, - Op: sql.DIV, - RHS: sql.NewIdent("meta.__." + key + ".c"), - }, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.SubExpression{ - &sql.IfelseStatement{ - Cond: sql.Exprs{ - &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.Empty{}, - }, - }, - Then: sql.Exprs{0}, - Else: sql.NewIdent(key), - }, - }, - }) - -} - -func tableStddev(set *sql.DataExpression, key string, val interface{}, when modify) { - - var op sql.Token - - switch when { - case _REMOVE: - op = sql.DEC - case _CHANGE: - op = sql.INC - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: op, - RHS: 1, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".t"), - Op: op, - RHS: val, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".m"), - Op: op, - RHS: &sql.BinaryExpression{ - LHS: val, - Op: sql.MUL, - RHS: val, - }, - }) - - // FIXME Need to ensure removed values update correctly - - switch when { - case _REMOVE: - op = sql.SUB // FIXME This is incorrect - case _CHANGE: - op = sql.ADD - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.FuncExpression{ - Name: "math.sqrt", - Args: sql.Exprs{ - &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: sql.MUL, - RHS: sql.NewIdent("meta.__." + key + ".m"), - }, - Op: sql.SUB, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".t"), - Op: sql.MUL, - RHS: sql.NewIdent("meta.__." + key + ".t"), - }, - }, - Op: sql.DIV, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: sql.MUL, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: sql.SUB, - RHS: 1, - }, - }, - }, - }, - }, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.SubExpression{ - &sql.IfelseStatement{ - Cond: sql.Exprs{ - &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.Empty{}, - }, - }, - Then: sql.Exprs{0}, - Else: sql.NewIdent(key), - }, - }, - }) - -} - -func tableVariance(set *sql.DataExpression, key string, val interface{}, when modify) { - - var op sql.Token - - switch when { - case _REMOVE: - op = sql.DEC - case _CHANGE: - op = sql.INC - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: op, - RHS: 1, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".t"), - Op: op, - RHS: val, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent("meta.__." + key + ".m"), - Op: op, - RHS: &sql.BinaryExpression{ - LHS: val, - Op: sql.MUL, - RHS: val, - }, - }) - - // FIXME Need to ensure removed values update correctly - - switch when { - case _REMOVE: - op = sql.SUB // FIXME This is incorrect - case _CHANGE: - op = sql.ADD - } - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: sql.MUL, - RHS: sql.NewIdent("meta.__." + key + ".m"), - }, - Op: sql.SUB, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".t"), - Op: sql.MUL, - RHS: sql.NewIdent("meta.__." + key + ".t"), - }, - }, - Op: sql.DIV, - RHS: &sql.BinaryExpression{ - LHS: sql.NewIdent("meta.__." + key + ".c"), - Op: sql.SUB, - RHS: 1, - }, - }, - Op: sql.DIV, - RHS: sql.NewIdent("meta.__." + key + ".c"), - }, - }) - - set.Data = append(set.Data, &sql.ItemExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.SubExpression{ - &sql.IfelseStatement{ - Cond: sql.Exprs{ - &sql.BinaryExpression{ - LHS: sql.NewIdent(key), - Op: sql.EQ, - RHS: &sql.Empty{}, - }, - }, - Then: sql.Exprs{0}, - Else: sql.NewIdent(key), - }, - }, - }) - -} diff --git a/db/update.go b/db/update.go deleted file mode 100644 index dc737c48..00000000 --- a/db/update.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeUpdate(ctx context.Context, stm *sql.UpdateStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - var what sql.Exprs - - for _, val := range stm.What { - w, err := e.fetch(ctx, val, nil) - if err != nil { - return nil, err - } - what = append(what, w) - } - - i := newIterator(e, ctx, stm, false) - - for _, w := range what { - - switch what := w.(type) { - - default: - return nil, fmt.Errorf("Can not execute UPDATE query using value '%v'", what) - - case *sql.Table: - key := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: what.TB} - i.processTable(ctx, key) - - case *sql.Ident: - key := &keys.Table{KV: KV, NS: e.ns, DB: e.db, TB: what.VA} - i.processTable(ctx, key) - - case *sql.Thing: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: what.ID} - i.processThing(ctx, key) - - case *sql.Model: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processModel(ctx, key, what) - - case *sql.Batch: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: what.TB, ID: nil} - i.processBatch(ctx, key, what) - - // Result of subquery - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, what) - - // Result of subquery with LIMIT 1 - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db} - i.processOther(ctx, key, []interface{}{what}) - - } - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchUpdate(ctx context.Context, stm *sql.UpdateStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeUpdate(ctx, stm) - if err != nil { - return nil, err - } - - switch len(out) { - case 1: - return data.Consume(out).Get(docKeyOne, docKeyId).Data(), nil - default: - return data.Consume(out).Get(docKeyAll, docKeyId).Data(), nil - } - -} - -func (d *document) runUpdate(ctx context.Context, stm *sql.UpdateStatement) (interface{}, error) { - - var ok bool - var err error - var met = _CREATE - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.lock(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.val.Exi() == true { - met = _UPDATE - } - - if ok, err = d.check(ctx, stm.Cond); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.merge(ctx, met, stm.Data); err != nil { - return nil, err - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.storeIndex(ctx); err != nil { - return nil, err - } - - if err = d.storeThing(ctx); err != nil { - return nil, err - } - - if err = d.table(ctx, met); err != nil { - return nil, err - } - - if err = d.lives(ctx, met); err != nil { - return nil, err - } - - if err = d.event(ctx, met); err != nil { - return nil, err - } - - return d.yield(ctx, stm, stm.Echo) - -} diff --git a/db/update_test.go b/db/update_test.go deleted file mode 100644 index 392d10f1..00000000 --- a/db/update_test.go +++ /dev/null @@ -1,664 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "time" - - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestUpdate(t *testing.T) { - - Convey("Update with invalid value", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE 1; - UPDATE "one"; - UPDATE ["many"]; - UPDATE [{value:"one"}]; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Status, ShouldEqual, "ERR") - So(res[1].Detail, ShouldEqual, "Can not execute UPDATE query using value '1'") - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Can not execute UPDATE query using value 'one'") - So(res[3].Status, ShouldEqual, "ERR") - So(res[3].Detail, ShouldEqual, "Can not execute UPDATE query using value '[many]'") - So(res[4].Status, ShouldEqual, "ERR") - So(res[4].Detail, ShouldEqual, "Can not execute UPDATE query using value '[map[value:one]]'") - - }) - - Convey("Update record when it exists", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE person:test; - UPDATE person:test; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - - }) - - Convey("Update unique record using `table`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE person, table("person"); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 0) - - }) - - Convey("Update specific record using `thing`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE person:test, thing("person", "test"); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 2) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 4) - So(data.Consume(res[1].Result[0]).Get("meta.tb").Data(), ShouldEqual, "person") - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldHaveLength, 4) - So(data.Consume(res[1].Result[1]).Get("meta.tb").Data(), ShouldEqual, "person") - - }) - - Convey("Update unique records using `batch`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE batch("person", ["1", "2", "person:3"]); - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 3) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[1].Result[2]).Get("meta.id").Data(), ShouldEqual, 3) - - }) - - Convey("Update unique records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:100|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 100) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(data.Consume(res[1].Result[99]).Get("meta.id").Data(), ShouldHaveLength, 20) - - }) - - Convey("Update sequential ascending records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:1..100|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 100) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[1].Result[99]).Get("meta.id").Data(), ShouldEqual, 100) - - }) - - Convey("Update sequential descending records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:100..1|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 100) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 100) - So(data.Consume(res[1].Result[99]).Get("meta.id").Data(), ShouldEqual, 1) - - }) - - Convey("Update sequential ascending negative-to-positive records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:-50..50|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 101) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, -50) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, -49) - So(data.Consume(res[1].Result[100]).Get("meta.id").Data(), ShouldEqual, 50) - - }) - - Convey("Update sequential ascending decimal records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:1,0.5..50|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 99) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 1) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, 1.5) - So(data.Consume(res[1].Result[98]).Get("meta.id").Data(), ShouldEqual, 50) - - }) - - Convey("Update sequential descending decimal records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:50,0.5..1|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 99) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, 50) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, 49.5) - So(data.Consume(res[1].Result[98]).Get("meta.id").Data(), ShouldEqual, 1) - - }) - - Convey("Update sequential ascending decimal negative-to-positive records using `model`", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:-50,0.5..50|; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 2) - So(res[1].Result, ShouldHaveLength, 201) - So(data.Consume(res[1].Result[0]).Get("meta.id").Data(), ShouldEqual, -50) - So(data.Consume(res[1].Result[1]).Get("meta.id").Data(), ShouldEqual, -49.5) - So(data.Consume(res[1].Result[200]).Get("meta.id").Data(), ShouldEqual, 50) - - }) - - Convey("Parsing same ID using ints, floats, and strings", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE person:1; - UPDATE person:1.0; - UPDATE person:⟨1⟩; - UPDATE person:⟨1.0⟩; - UPDATE person:⟨1.0000⟩; - SELECT name FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 7) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 1) - So(res[5].Result, ShouldHaveLength, 1) - So(res[6].Result, ShouldHaveLength, 1) - - }) - - Convey("Updating with a timeout of 1ms returns an error", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPDATE |person:1..1000| TIMEOUT 1ms; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 0) - So(res[2].Result, ShouldHaveLength, 0) - So(res[1].Status, ShouldEqual, "ERR_TO") - So(res[1].Detail, ShouldEqual, "Query timeout of 1ms exceeded") - - }) - - Convey("Update a record using CONTENT", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET test="text"; - UPDATE person:test CONTENT {"other":true}; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[1].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, true) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update records using CONTENT", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - UPDATE person CONTENT {"other":true}; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[1].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[0]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[1]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[2]).Get("other").Data(), ShouldEqual, true) - So(res[5].Result, ShouldHaveLength, 3) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[0]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[1]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[2]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update a record using CONTENT stored in a $param", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - Let data = {"other":true}; - CREATE person:test SET test="text"; - UPDATE person:test CONTENT $data; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, true) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[0]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update a record using MERGE", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET test="text"; - UPDATE person:test MERGE {"other":true}; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[1].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, true) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update records using MERGE", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - UPDATE person MERGE {"other":true}; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[4].Result[0]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[4].Result[1]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[4].Result[2]).Get("other").Data(), ShouldEqual, true) - So(res[5].Result, ShouldHaveLength, 3) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[1]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[2]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update a record using MERGE stored in a $param", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = {"other":true}; - CREATE person:test SET test="text"; - UPDATE person:test MERGE $data; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, true) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[4].Result[0]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update a record using DIFF", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET test="text"; - UPDATE person:test DIFF [{"op":"add","path":"/other","value":true}]; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[1].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, true) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update a record using DIFF stored in a $param", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = [{"op":"add","path":"/other","value":true}]; - CREATE person:test SET test="text"; - UPDATE person:test DIFF $data; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[2].Result[0]).Get("other").Data(), ShouldEqual, nil) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[3].Result[0]).Get("other").Data(), ShouldEqual, true) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "text") - So(data.Consume(res[4].Result[0]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update records using DIFF", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - UPDATE person DIFF [{"op":"add","path":"/other","value":true}]; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[4].Result[0]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[4].Result[1]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[4].Result[2]).Get("other").Data(), ShouldEqual, true) - So(res[5].Result, ShouldHaveLength, 3) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[1]).Get("other").Data(), ShouldEqual, true) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[2]).Get("other").Data(), ShouldEqual, true) - - }) - - Convey("Update a record using NULL to unset a field", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET test = true; - UPDATE person:test SET test = NULL; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, true) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, nil) - _, ok := res[2].Result[0].(map[string]interface{})["test"] - So(ok, ShouldEqual, true) - - }) - - Convey("Update a record using VOID to remove a field", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET test = true; - UPDATE person:test SET test = VOID; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, true) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, nil) - _, ok := res[2].Result[0].(map[string]interface{})["test"] - So(ok, ShouldEqual, false) - - }) - - Convey("Update a set of records, but only if they exist", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test = true; - UPDATE |person:1..3| SET test = false WHERE id != VOID; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, true) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, false) - - }) - - Convey("Update a set of records using CONTENT with embedded times / records", t, func() { - - clock, _ := time.Parse(time.RFC3339, "1987-06-22T08:00:00.123456789Z") - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test CONTENT {"time":"1987-06-22T08:00:00.123456789Z","test":"person:other"}; - SELECT * FROM person; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("time").Data(), ShouldEqual, clock) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldResemble, sql.NewThing("person", "other")) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("time").Data(), ShouldEqual, clock) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldResemble, sql.NewThing("person", "other")) - - }) - -} diff --git a/db/upsert.go b/db/upsert.go deleted file mode 100644 index 64c1cb92..00000000 --- a/db/upsert.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "fmt" - - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (e *executor) executeUpsert(ctx context.Context, stm *sql.UpsertStatement) ([]interface{}, error) { - - if err := e.access(ctx, cnf.AuthNO); err != nil { - return nil, err - } - - data, err := e.fetch(ctx, stm.Data, nil) - if err != nil { - return nil, err - } - - i := newIterator(e, ctx, stm, false) - - switch data := data.(type) { - - default: - return nil, fmt.Errorf("Can not execute UPSERT query using value '%v'", data) - - case []interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: stm.Into.TB} - i.processArray(ctx, key, data) - - case map[string]interface{}: - key := &keys.Thing{KV: KV, NS: e.ns, DB: e.db, TB: stm.Into.TB} - i.processArray(ctx, key, []interface{}{data}) - - } - - return i.Yield(ctx) - -} - -func (e *executor) fetchUpsert(ctx context.Context, stm *sql.UpsertStatement, doc *data.Doc) (interface{}, error) { - - ctx = dive(ctx) - - if doc != nil { - vars := data.New() - vars.Set(doc.Data(), varKeyParent) - if subs := ctx.Value(ctxKeySubs); subs != nil { - if subs, ok := subs.(*data.Doc); ok { - vars.Set(subs.Get(varKeyParents).Data(), varKeyParents) - } - } else { - vars.Array(varKeyParents) - } - vars.Append(doc.Data(), varKeyParents) - ctx = context.WithValue(ctx, ctxKeySubs, vars) - } - - out, err := e.executeUpsert(ctx, stm) - if err != nil { - return nil, err - } - - switch len(out) { - case 1: - return data.Consume(out).Get(docKeyOne, docKeyId).Data(), nil - default: - return data.Consume(out).Get(docKeyAll, docKeyId).Data(), nil - } - -} - -func (d *document) runUpsert(ctx context.Context, stm *sql.UpsertStatement) (interface{}, error) { - - var ok bool - var err error - var met = _CREATE - - if err = d.init(ctx); err != nil { - return nil, err - } - - if err = d.lock(ctx); err != nil { - return nil, err - } - - if err = d.setup(ctx); err != nil { - return nil, err - } - - if d.val.Exi() == true { - met = _UPDATE - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.merge(ctx, met, nil); err != nil { - return nil, err - } - - if ok, err = d.allow(ctx, met); err != nil { - return nil, err - } else if ok == false { - return nil, nil - } - - if err = d.storeIndex(ctx); err != nil { - return nil, err - } - - if err = d.storeThing(ctx); err != nil { - return nil, err - } - - if err = d.table(ctx, met); err != nil { - return nil, err - } - - if err = d.lives(ctx, met); err != nil { - return nil, err - } - - if err = d.event(ctx, met); err != nil { - return nil, err - } - - return d.yield(ctx, stm, stm.Echo) - -} diff --git a/db/upsert_test.go b/db/upsert_test.go deleted file mode 100644 index 81c9ef67..00000000 --- a/db/upsert_test.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestUpsert(t *testing.T) { - - Convey("Upsert with invalid value", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - UPSERT 1 INTO user; - UPSERT "one" INTO user; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 3) - So(res[1].Status, ShouldEqual, "ERR") - So(res[1].Detail, ShouldEqual, "Can not execute UPSERT query using value '1'") - So(res[2].Status, ShouldEqual, "ERR") - So(res[2].Detail, ShouldEqual, "Can not execute UPSERT query using value 'one'") - - }) - - Convey("Upsert a set of ids from one table to another table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - UPSERT (SELECT id FROM person) INTO user; - SELECT * FROM person, user; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[4].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - So(res[5].Result, ShouldHaveLength, 6) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 1)) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 2)) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 3)) - So(data.Consume(res[5].Result[3]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[3]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[5].Result[4]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[4]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[5].Result[5]).Get("test").Data(), ShouldEqual, nil) - So(data.Consume(res[5].Result[5]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - - }) - - Convey("Upsert a set of records from one table to another table", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:1 SET test="one"; - CREATE person:2 SET test="two"; - CREATE person:3 SET test="tre"; - UPSERT (SELECT * FROM person) INTO user; - SELECT * FROM person, user; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 6) - So(res[1].Result, ShouldHaveLength, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(res[3].Result, ShouldHaveLength, 1) - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[4].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[4].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[4].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[4].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[4].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - So(res[5].Result, ShouldHaveLength, 6) - So(data.Consume(res[5].Result[0]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[0]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 1)) - So(data.Consume(res[5].Result[1]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[1]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 2)) - So(data.Consume(res[5].Result[2]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[2]).Get("id").Data(), ShouldResemble, sql.NewThing("person", 3)) - So(data.Consume(res[5].Result[3]).Get("test").Data(), ShouldEqual, "one") - So(data.Consume(res[5].Result[3]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 1)) - So(data.Consume(res[5].Result[4]).Get("test").Data(), ShouldEqual, "two") - So(data.Consume(res[5].Result[4]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 2)) - So(data.Consume(res[5].Result[5]).Get("test").Data(), ShouldEqual, "tre") - So(data.Consume(res[5].Result[5]).Get("id").Data(), ShouldResemble, sql.NewThing("user", 3)) - - }) - - Convey("Upsert a set of records from data with an ID", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = { "id": 360, "admin":true, "login":"joe" }; - UPSERT $data INTO users; - UPSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - - }) - - Convey("Upsert a set of records from data without an ID", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = { "admin":true, "login":"tom" }; - UPSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - - }) - - Convey("Upsert a set of records from an array of data with IDs", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = [ - { "id": 360, "admin":true, "login":"joe" }, - { "id": 200, "admin":false, "login":"mike" }, - { "id": "test", "admin":false, "login":"tester" }, - ]; - UPSERT $data INTO users; - UPSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[2].Result, ShouldHaveLength, 3) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - So(data.Consume(res[2].Result[1]).Get("login").Data(), ShouldEqual, "mike") - So(data.Consume(res[2].Result[1]).Get("meta.id").Data(), ShouldEqual, 200) - So(data.Consume(res[2].Result[2]).Get("login").Data(), ShouldEqual, "tester") - So(data.Consume(res[2].Result[2]).Get("meta.id").Data(), ShouldEqual, "test") - So(res[3].Result, ShouldHaveLength, 3) - So(data.Consume(res[3].Result[0]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldEqual, 360) - So(data.Consume(res[3].Result[1]).Get("login").Data(), ShouldEqual, "mike") - So(data.Consume(res[3].Result[1]).Get("meta.id").Data(), ShouldEqual, 200) - So(data.Consume(res[3].Result[2]).Get("login").Data(), ShouldEqual, "tester") - So(data.Consume(res[3].Result[2]).Get("meta.id").Data(), ShouldEqual, "test") - So(res[4].Result, ShouldHaveLength, 3) - So(data.Consume(res[4].Result[0]).Get("login").Data(), ShouldEqual, "mike") - So(data.Consume(res[4].Result[0]).Get("meta.id").Data(), ShouldEqual, 200) - So(data.Consume(res[4].Result[1]).Get("login").Data(), ShouldEqual, "joe") - So(data.Consume(res[4].Result[1]).Get("meta.id").Data(), ShouldEqual, 360) - So(data.Consume(res[4].Result[2]).Get("login").Data(), ShouldEqual, "tester") - So(data.Consume(res[4].Result[2]).Get("meta.id").Data(), ShouldEqual, "test") - - }) - - Convey("Upsert a set of records from an array of data without IDs", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - LET data = [ - { "admin":true, "login":"tom" }, - ]; - UPSERT $data INTO users; - SELECT * FROM users; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 4) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[2].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - So(res[3].Result, ShouldHaveLength, 1) - So(data.Consume(res[3].Result[0]).Get("login").Data(), ShouldEqual, "tom") - So(data.Consume(res[3].Result[0]).Get("meta.id").Data(), ShouldHaveLength, 20) - - }) - -} diff --git a/db/use.go b/db/use.go deleted file mode 100644 index 5be700e7..00000000 --- a/db/use.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/sql" -) - -func (e *executor) executeUse(ctx context.Context, stm *sql.UseStatement) (out []interface{}, err error) { - - // If a NAMESPACE has been defined, then - // process the permissions, or return an - // error if we can't specify a namespace. - - if len(stm.NS) > 0 { - - if perm(ctx) == cnf.AuthKV { - e.ns = stm.NS - } - - if perm(ctx) == cnf.AuthNS { - if e.ns != stm.NS { - err = new(QueryError) - } - } - - if perm(ctx) == cnf.AuthDB { - if e.ns != stm.NS { - err = new(QueryError) - } - } - - if perm(ctx) == cnf.AuthSC { - if e.ns != stm.NS { - err = new(QueryError) - } - } - - if perm(ctx) == cnf.AuthNO { - e.ns = stm.NS - } - - } - - // If a DATABASE has been defined, then - // process the permissions, or return an - // error if we can't specify a database. - - if len(stm.DB) > 0 { - - if perm(ctx) == cnf.AuthKV { - e.db = stm.DB - } - - if perm(ctx) == cnf.AuthNS { - e.db = stm.DB - } - - if perm(ctx) == cnf.AuthDB { - if e.db != stm.DB { - err = new(QueryError) - } - } - - if perm(ctx) == cnf.AuthSC { - if e.db != stm.DB { - err = new(QueryError) - } - } - - if perm(ctx) == cnf.AuthNO { - e.db = stm.DB - } - - } - - if err != nil { - e.ns, e.db = "", "" - } - - return - -} diff --git a/db/vars.go b/db/vars.go deleted file mode 100644 index 1d5d2e0a..00000000 --- a/db/vars.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "errors" - "runtime" -) - -type method int8 - -const ( - _SELECT method = iota - _CREATE - _UPDATE - _DELETE -) - -type modify int8 - -const ( - _REMOVE modify = iota - _CHANGE -) - -const ( - docKeyId = "id" - docKeyOne = "0" - docKeyAll = "*" -) - -const ( - logKeyId = "id" - logKeyNS = "ns" - logKeyDB = "db" - logKeySql = "sql" - logKeyExe = "exe" - logKeyKind = "kind" - logKeyVars = "vars" - logKeyTime = "time" - logKeySpan = "span" - logKeyTrace = "trace" - logKeyError = "error" - logKeyStack = "stack" - logKeyFibre = "fibre" -) - -const ( - ctxKeyId = "id" - ctxKeyDive = "dive" - ctxKeyVars = "vars" - ctxKeySubs = "subs" - ctxKeySpec = "spec" - ctxKeyAuth = "auth" - ctxKeyKind = "kind" - ctxKeyForce = "force" - ctxKeyFibre = "fibre" - ctxKeyVersion = "version" -) - -const ( - varKeyId = "id" - varKeyIp = "ip" - varKeyEnv = "ENV" - varKeyAuth = "auth" - varKeyUniq = "uniq" - varKeyThis = "this" - varKeyScope = "scope" - varKeyValue = "value" - varKeyAfter = "after" - varKeyBefore = "before" - varKeyMethod = "method" - varKeyOrigin = "origin" - varKeyParent = "parent" - varKeyParents = "parents" - varKeySession = "session" -) - -var ( - // workerCount specifies how many workers should be used - // to process each query statement concurrently. - workerCount = runtime.NumCPU() - - // maxRecursiveQueries specifies how many queries will be - // processed recursively before the query is cancelled. - maxRecursiveQueries = uint32(16) - - // queryIdentFailed occurs when a permission query asks - // for a field, meaning a document has to be fetched. - queryIdentFailed = errors.New("Found ident but no doc available") - - // errQueryNotExecuted occurs when a transaction has - // failed, and the following queries are not executed. - errQueryNotExecuted = errors.New("Query not executed") - - // errRaceCondition occurs when a record which is locked - // for editing, is updated from within a subquery. - errRaceCondition = errors.New("Failed to update the same document recursively") - - // errRecursiveOverload occurs when too many subqueries - // are executed within one other, causing an endless loop. - errRecursiveOverload = errors.New("Infinite loop when running recursive subqueries") - - // errFeatureNotImplemented occurs when a feature which - // has not yet been implemented, has been used in a query. - errFeatureNotImplemented = errors.New("Feature is not yet implemented") - - // paramSearchKeys specifies the order in which context - // variables should be checked for any specified value. - paramSearchKeys = []string{ctxKeySpec, ctxKeySubs, ctxKeyVars} -) diff --git a/db/yield.go b/db/yield.go deleted file mode 100644 index 38276740..00000000 --- a/db/yield.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func (d *document) cold(ctx context.Context) (doc *data.Doc, err error) { - - // We need to copy the document so that - // we can add and remove the fields which - // are relevant to the particular query. - - doc = d.initial.Copy() - - // If we are not authenticated using DB, - // NS, or KV level, then we need to check - // document permissions for this query. - - if err = d.perms(ctx, doc); err != nil { - return nil, err - } - - return - -} - -func (d *document) cnow(ctx context.Context) (doc *data.Doc, err error) { - - // We need to copy the document so that - // we can add and remove the fields which - // are relevant to the particular query. - - doc = d.current.Copy() - - // If we are not authenticated using DB, - // NS, or KV level, then we need to check - // document permissions for this query. - - if err = d.perms(ctx, doc); err != nil { - return nil, err - } - - return - -} - -func (d *document) yield(ctx context.Context, stm sql.Statement, output sql.Token) (interface{}, error) { - - var exps sql.Fields - var grps sql.Groups - var fchs sql.Fetchs - - switch stm := stm.(type) { - case *sql.LiveStatement: - exps = stm.Expr - fchs = stm.Fetch - case *sql.SelectStatement: - exps = stm.Expr - grps = stm.Group - fchs = stm.Fetch - } - - // If there are no field expressions - // then this was not a LIVE or SELECT - // query, and therefore the query will - // have an output format specified. - - if len(exps) == 0 { - - switch output { - default: - return nil, nil - - case sql.AFTER: - - doc, err := d.cnow(ctx) - if err != nil { - return nil, err - } - return doc.Data(), nil - - case sql.BEFORE: - - doc, err := d.cold(ctx) - if err != nil { - return nil, err - } - return doc.Data(), nil - - } - - } - - // But if there are field expresions - // then this query is a LIVE or SELECT - // query, and we must output only the - // desired fields in the output. - - var out = data.New() - - doc, err := d.cnow(ctx) - if err != nil { - return nil, err - } - - // First of all, check to see if an ALL - // expression has been specified, and if - // it has then use the full document. - - for _, e := range exps { - if _, ok := e.Expr.(*sql.All); ok { - out = doc - break - } - } - - // Ensure that all output fields are - // available in subsequent expressions - // using the $this parameter. - - vars := data.New() - vars.Set(out.Data(), varKeyThis) - ctx = context.WithValue(ctx, ctxKeySpec, vars) - - // Next let's see the field expressions - // which have been requested, and add - // these to the output document. - - for _, e := range exps { - - switch v := e.Expr.(type) { - case *sql.All: - break - default: - - // If the query has a GROUP BY expression - // then let's check if this is an aggregate - // function, and if it is then pass the - // first argument directly through. - - if len(grps) > 0 { - if f, ok := e.Expr.(*sql.FuncExpression); ok && f.Aggr { - v, err := d.i.e.fetch(ctx, f.Args[0], doc) - if err != nil { - return nil, err - } - out.Set(v, f.String()) - continue - } - } - - // Otherwise treat the field normally, and - // calculate the value to be inserted into - // the final output document. - - o, err := d.i.e.fetch(ctx, v, doc) - if err != nil { - return nil, err - } - - switch o { - case doc: - out.Set(nil, e.Field) - default: - out.Set(o, e.Field) - } - - } - - } - - // Finally let's see if there are any - // FETCH expressions, so that we can - // follow links to other records. - - for _, e := range fchs { - - switch v := e.Expr.(type) { - case *sql.All: - break - case *sql.Ident: - - out.Walk(func(key string, val interface{}, exi bool) error { - - switch res := val.(type) { - case []interface{}: - val := make([]interface{}, len(res)) - for k, v := range res { - switch tng := v.(type) { - case *sql.Thing: - val[k], _ = d.i.e.fetchThing(ctx, tng, doc) - default: - val[k] = v - } - } - out.Set(val, key) - case *sql.Thing: - val, _ = d.i.e.fetchThing(ctx, res, doc) - out.Set(val, key) - } - - return nil - - }, v.VA) - - } - - } - - // Remove all temporary metadata from - // the record. This is not visible when - // outputting, but is stored in the DB. - - doc.Del("meta.__") - - // Output the document with the correct - // specified fields, linked records and - // any aggregated group by clauses. - - return out.Data(), nil - -} diff --git a/db/yield_test.go b/db/yield_test.go deleted file mode 100644 index 04151a8b..00000000 --- a/db/yield_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package db - -import ( - "testing" - - "github.com/surrealdb/surrealdb/util/data" - . "github.com/smartystreets/goconvey/convey" -) - -func TestYield(t *testing.T) { - - Convey("Yield different responses when modifying a record", t, func() { - - setupDB(1) - - txt := ` - USE NS test DB test; - CREATE person:test SET test=1 RETURN AFTER; - UPDATE person:test SET test=2 RETURN BEFORE; - UPDATE person:test SET test=3 RETURN NONE; - DELETE person:test RETURN BEFORE; - ` - - res, err := Execute(permsKV(), txt, nil) - So(err, ShouldBeNil) - So(res, ShouldHaveLength, 5) - So(res[1].Result, ShouldHaveLength, 1) - So(data.Consume(res[1].Result[0]).Get("test").Data(), ShouldEqual, 1) - So(res[2].Result, ShouldHaveLength, 1) - So(data.Consume(res[2].Result[0]).Get("test").Data(), ShouldEqual, 1) - So(res[3].Result, ShouldHaveLength, 0) - So(res[4].Result, ShouldHaveLength, 1) - So(data.Consume(res[4].Result[0]).Get("test").Data(), ShouldEqual, 3) - - }) - -} diff --git a/doc/ENDPOINTS.md b/doc/ENDPOINTS.md deleted file mode 100644 index 445d05e6..00000000 --- a/doc/ENDPOINTS.md +++ /dev/null @@ -1,62 +0,0 @@ -# Endpoints - -This document describes RESTful http endpoints which can be used to query and manipulate the database. - ---- - -### SQL - -The SQL endpoint allows you to query the database using any SQL query supported by Surreal. The content body must contain the properly formatted SQL queries which should be executed by the database. It may include a batch of SQL statements separated by a semicolon. - -- `POST` `https://api.surreal.io/sql` - ---- - -### Key Value - -The key value endpoints allow you to manipulate the database records without needing to use SQL. It only includes a small portion of the functionality available with SQL queries. The endpoints enable you to use the database as if it were an API, using multi-tenancy separation, and multi-level authentication for preventing access to specific data within a database. - -- `GET` `https://api.surreal.io/key/{table}` -```sql -SELECT * FROM {table} -``` - -- `POST` `https://api.surreal.io/key/{table}` -```sql -CREATE {table} -``` - -- `DELETE` `https://api.surreal.io/key/{table}` -```sql -DELETE {table} -``` - -- `GET` `https://api.surreal.io/key/{table}/{key}` -```sql -SELECT * FROM @{table}:{key} -``` - -- `PUT` `https://api.surreal.io/key/{table}/{key}` -```sql -UPDATE @{table}:{key} CONTENT {} RETURN AFTER -``` - -- `POST` `https://api.surreal.io/key/{table}/{key}` -```sql -CREATE @{table}:{key} CONTENT {} RETURN AFTER -``` - -- `PATCH` `https://api.surreal.io/key/{table}/{key}` -```sql -MODIFY @{table}:{key} DIFF {} RETURN AFTER -``` - -- `TRACE` `https://api.surreal.io/key/{table}/{key}` -```sql -SELECT HISTORY FROM @{table}:{key} -``` - -- `DELETE` `https://api.surreal.io/key/{table}/{key}` -```sql -DELETE @{table}:{key} -``` \ No newline at end of file diff --git a/doc/QUERIES.md b/doc/QUERIES.md deleted file mode 100644 index d001e7cc..00000000 --- a/doc/QUERIES.md +++ /dev/null @@ -1,409 +0,0 @@ -# Queries - -This document describes example SQL queries which can be used to query the database. - -#### USE - -```sql --- Specify a namespace to use for future sql commands -USE NAMESPACE abcum; --- Specify a database to use for future sql commands -USE DATABASE acreon; --- Specify a namespace and database to use in one sql query -USE NAMESPACE abcum DATABASE acreon; -``` - -#### INFO - -```sql --- Retrive info for the namespace -INFO FOR NAMESPACE; --- Retrive info for the database -INFO FOR DATABASE; --- Retrive info for a specific table -INFO FOR TABLE person; -``` - -#### DEFINE NAMESPACE - -```sql --- Define a namespace -DEFINE NAMESPACE abcum; --- Remove a namespace and all data -REMOVE NAMESPACE abcum; -``` - -#### DEFINE DATABASE - -```sql --- Define a database -DEFINE DATABASE acreon; --- Remove a database and all data -REMOVE DATABASE acreon; -``` - -#### DEFINE LOGIN - -```sql --- Define a user account on the namespace -DEFINE LOGIN `tobie@abcum.com` ON NAMESPACE PASSWORD '192837192837192837'; --- Remove a user account from the namespace -REMOVE LOGIN `tobie@abcum.com` ON NAMESPACE; - --- Define a user account on the database -DEFINE LOGIN `tobie@abcum.com` ON DATABASE PASSWORD '192837192837192837'; --- Remove a user account from the database -REMOVE LOGIN `tobie@abcum.com` ON DATABASE; -``` - -#### DEFINE TOKEN - -```sql --- Define a signing token on the namespace -DEFINE TOKEN `default` ON NAMESPACE TYPE HS256 VALUE "secretkey"; --- Define a signing token public key on the namespace -DEFINE TOKEN `default` ON NAMESPACE TYPE RS256 VALUE "-----BEGIN PUBLIC KEY----- MIGfMA0G..."; --- Remove a signing token from the namespace -REMOVE TOKEN `default` ON NAMESPACE; - --- Define a signing token on the database -DEFINE TOKEN `default` ON DATABASE TYPE HS256 VALUE "secretkey"; --- Define a signing token public key on the database -DEFINE TOKEN `default` ON DATABASE TYPE HS256 VALUE "-----BEGIN PUBLIC KEY----- MIGfMA0G..."; --- Remove a signing token from the database -REMOVE TOKEN `default` ON DATABASE; -``` - -#### DEFINE SCOPE - -```sql --- Define an authentication scope named 'account' -DEFINE SCOPE account SESSION 1h SIGNUP AS (CREATE admin SET email=$user, pass=bcrypt.generate($pass), account=(UPDATE AND UPSERT @account:$account SET name=$accountname)) SIGNIN AS (SELECT * FROM admin WHERE email=$user AND bcrypt.compare(pass, $pass)); --- Remove the authentication scope named 'account' -REMOVE SCOPE account; - --- Define an authentication scope named 'profile' -DEFINE SCOPE profile SESSION 24h SIGNUP AS (CREATE person SET email=$user, pass=bcrypt.generate($pass)) SIGNIN AS (SELECT * FROM person WHERE email=$user AND bcrypt.compare(pass, $pass)); --- Remove the authentication scope named 'profile' -REMOVE SCOPE profile; -``` - -#### DEFINE TABLE - -```sql --- Define a new table on the database -DEFINE TABLE person; --- Remove a table from the database -REMOVE TABLE person; - --- Define a new table as schemaless -DEFINE TABLE items SCHEMALESS; --- Define a new table as schemafull -DEFINE TABLE items SCHEMAFULL; - -DEFINE TABLE shot SHARD ON course, hole; - -SELECT * FROM shot::{course=$course, hole=$hole}; -SELECT * FROM shot WHERE course = $course AND hole = $hole; - --- Define a new table as with no scope permissions -DEFINE TABLE items PERMISSIONS NONE; --- Define a new table as with full scope permissions -DEFINE TABLE items PERMISSIONS FULL; --- Define a new table as with advanced scope permissions -DEFINE TABLE items PERMISSIONS FOR select FULL FOR delete NONE FOR create, update WHERE $auth.type = "admin"; -``` - -#### DEFINE FIELD - -```sql --- Define a new field on a database table -DEFINE FIELD age ON person; --- Remove a field from a database table -REMOVE FIELD name ON person; - --- Define a new field with a type -DEFINE FIELD age ON person TYPE number; --- Define a new embedded field with type -DEFINE FIELD name.first ON person TYPE string; --- Define a new field on an array of objects -DEFINE FIELD emails.*.value ON person TYPE email; --- Define a new field with min and max allowed values -DEFINE FIELD age ON person TYPE number MIN 0 MAX 100; --- Define a new field which can not be specified as NULL -DEFINE FIELD age ON person TYPE number MIN 0 MAX 100 NOTNULL; --- Define a new field which will fail if not the correct type -DEFINE FIELD age ON person TYPE number MIN 0 MAX 100 VALIDATE; --- Define a new field which is not able to be changed once defined -DEFINE FIELD age ON person TYPE number MIN 0 MAX 100 NOTNULL VALIDATE READONLY; --- Define a new field which defaults to a specified value if not defined -DEFINE FIELD country ON address TYPE string DEFAULT "GBR"; --- Define a new field into which any data put must match a regular expression -DEFINE FIELD iso ON output TYPE string MATCH /^[A-Z]{3}$/; --- Define a new field into which any data put must match a specific set of values -DEFINE FIELD kind ON address TYPE custom ENUM ["home","work"]; --- Define a new computed field which will autoupdate when any dependent fields change -DEFINE FIELD fullname ON person TYPE string CODE "return [doc.data.firstname, doc.data.lastname].join(' ');"; - --- Define a new field which can not be viewed or edited by any user authenticated by scope -DEFINE FIELD password ON person TYPE string PERMISSIONS NONE; --- Define a new field which has specific access methods for any user authenticated by scope -DEFINE FIELD notes ON person TYPE string PERMISSIONS FOR select WHERE $auth.accountid = accountid FOR create, update, delete WHERE $auth.accountid = accountid AND $auth.type = "admin"; -``` - -#### DEFINE INDEX - -```sql --- Define an index for a table -DEFINE INDEX sortable ON person COLUMNS name; --- Remove an index from a table -REMOVE INDEX sortable ON person; - --- Define a unique index on a table -DEFINE INDEX sortable ON person COLUMNS uuid UNIQUE; --- Define a compound index with multiple columns -DEFINE INDEX sortable ON person COLUMNS firstname, lastname; - --- Define an index for all values in an array set -DEFINE INDEX tags ON person COLUMNS tags.*; --- Define an index for all values in each object in an array set -DEFINE INDEX tags ON person COLUMNS tags.*.value; -``` - -#### DEFINE VIEW - -```sql --- Define an aggregated view on a database -DEFINE VIEW ages AS SELECT count(*), min(age), max(age) FROM person; --- Remove an aggregated view from a database -REMOVE VIEW ages; - --- Define an aggregated view with a where clause -DEFINE VIEW ages AS SELECT count(*), min(age), max(age) FROM person WHERE age > 18; --- Define an aggregated view with a where clause, and a group-by clause -DEFINE VIEW ages AS SELECT count(*), min(age), max(age) FROM person WHERE age > 18 GROUP BY nationality; --- Define an aggregated view with a where clause, and multiple group-by clauses -DEFINE VIEW ages AS SELECT count(*), min(age), max(age) FROM person WHERE age > 18 GROUP BY nationality, gender; -``` - -#### LIVE - -```sql --- Define a live query for a table -LIVE SELECT * FROM person; --- Remove a live query from a table -KILL "183047103847103847"; - --- Define a live query for a table, only for records which match a condition -LIVE SELECT name, age, country FROM person WHERE age > 18 AND age < 60; -``` - -#### CREATE - -```sql --- Create a new record -CREATE person; --- Create a new record and set some fields -CREATE person SET age=28, name='Tobie'; --- Create a new record and merge the record content -CREATE person MERGE {"firstname":"Tobie", "lastname":"Morgan Hitchcock"}; --- Create a new record and specify the full record content -CREATE person CONTENT {"firstname":"Tobie", "lastname":"Morgan Hitchcock"}; - --- Create a new specific record -CREATE @person:id; --- Create a new specific record and set some fields -CREATE @person:id SET age = 28, name = 'Tobie'; --- Create a new specific record and set some fields, along with an empty set -CREATE @person:id SET age = 28, name = 'Tobie', tags = []; --- Create a new specific record and set some fields, along with a set with 1 element -CREATE @person:id SET age = 28, name = 'Tobie', tags = ['old']; - --- Create multiple records in one query -CREATE person, person, person; --- Create multiple specific records in -CREATE @person:one, @person:two; -``` - -#### UPDATE - -```sql --- Update a table, ensuring all defined fields are up-to-date -UPDATE person; --- Update a table, setting a field to null on all records -UPDATE person SET age=NULL; --- Update a table, removing a field completely from all records -UPDATE person SET age=VOID; --- Update a table, removing a field completely from all records that match a condition -UPDATE person SET age=VOID WHERE age < 18; - --- Update a specific record, ensuring it exists -UPDATE @person:id --- Update a specific record, and erase all record data -UPDATE @person:id CONTENT {}; --- Update a specific record, and set some fields -UPDATE @person:id SET age = 28, name = 'Tobie'; --- Update a specific record, and set a field as NULL -UPDATE @person:id SET age = 28, name = 'Tobie', tags = NULL; --- Update a specific record, and set a field to an empty set -UPDATE @person:id SET age = 28, name = 'Tobie', tags = []; --- Update a specific record, and set a field to a set with 1 element -UPDATE @person:id SET age = 28, name = 'Tobie', tags = ['old']; --- Update a specific record, and add 'new' to the `tags` set and removes 'old' from the `tags` set -UPDATE @person:id SET age = 28, name = 'Tobie', tags += ['new'], tags -= ['old']; - --- Update multiple records in one query, ensuring both exist -UPDATE @person:one, @person:two; - --- Update a specific record and ensure the `emails` field is a set -UPDATE @person:id SET emails = []; --- Update a specific record and add an object to the `emails` set -UPDATE @person:id SET emails += {type: "work", value: "tobie@abcum.co.uk"}; --- Update a specific record and set the vaue of the first object in the `emails` set -UPDATE @person:id SET emails[0].value = "tobie@abcum.com"; --- Update a specific record and remove the object from the `emails` set -UPDATE @person:id SET emails -= {type: "work", value: "tobie@abcum.com"}; -``` - -#### DELETE - -```sql --- Delete all records in a table -DELETE person; --- Delete all records in a table that match a condition -DELETE person WHERE age < 18; - --- Delete a specific record from a table -DELETE @person:id; --- Delete a specific record, if the condition matches -DELETE @person:id WHERE age < 18; - --- Delete multiple records in one statement -DELETE @person:one, @person:two; -``` - -#### RELATE - -```sql --- Define an edge connection between two records -RELATE friend FROM @person:one TO @person:two; --- Define an edge connection between two records, ensuring only one edge of this type exists -RELATE friend FROM @person:one TO @person:two UNIQUE; --- Define an edge connection between two records, created in subqueries -RELATE friend FROM (CREATE person) TO (CREATE person); -``` - -#### BEGIN, CANCEL, COMMIT - -```sql --- Begin a new transaction -BEGIN; --- Cancel a transaction -CANCEL; --- Commit a transaction -COMMIT; - --- Define a unique index -DEFINE INDEX languages ON country COLUMNS languages.* UNIQUE; -CREATE @country:GBR SET name="Great Britain" languages=["english", "welsh", "scottish"]; -CREATE @country:FRA SET name="France" languages=["french"]; - --- Define a transaction that will fail, without any changes to the database -BEGIN; -CREATE @country:BRA SET name="Brazil" languages=["portugese"]; -CREATE @country:USA SET name="United States of America" languages=["english"]; -CREATE @country:DEU SET name="Germany" languages="german"; -COMMIT; -``` - -#### LET, RETURN - -```sql --- Define a new variable as a new person record -LET person1 = (CREATE person); --- Define a 2nd variable as a new person record -LET person2 = (CREATE person); --- Define a 3rd variable as a graph connection between the 1st and 2nd variables -LET edge = (RELATE friend FROM $person TO $person2); --- Return only the first two people, ignoring the graph edge -RETURN $person1, $person2; -``` - -#### SELECT - -```sql --- Select all records from a table -SELECT * FROM person; --- Select all records where the condition matches -SELECT * FROM person WHERE age > 18; --- Select all records and specify a dynamically calculated field -SELECT ((celsius*2)+30) AS fahrenheit FROM temperatues; --- Select all records where the age is greater than the age of another specific record -SELECT * FROM person WHERE age >= person:tobie; - -SELECT * FROM shot::{course=$course, hole=$hole} - --- Select all records where the `tags` set contains "tag" -SELECT * FROM person WHERE tags ∋ "tag"; -SELECT * FROM person WHERE tags ~ "tag"; -SELECT * FROM person WHERE tags CONTAINS "tag"; -SELECT * FROM person WHERE "tag" ∈ tags; -SELECT * FROM person WHERE "tag" IS IN tags; --- Select all records where the `tags` set does not contain "tag" -SELECT * FROM person WHERE tags ∌ "tag"; -SELECT * FROM person WHERE tags !~ "tag"; -SELECT * FROM person WHERE tags CONTAINS NOT "tag"; -SELECT * FROM person WHERE "tag" ∉ tags; -SELECT * FROM person WHERE "tag" IS NOT IN tags; --- Select all records where the `tags` set contains "tag1" AND "tag2" -SELECT * FROM person WHERE tags ⊇ ["tag1", "tag2"]; -SELECT * FROM person WHERE tags CONTAINSALL ["tag1", "tag2"]; --- Select all records where the `tags` set contains "tag1" OR "tag2" -SELECT * FROM person WHERE tags ⊃ ["tag1", "tag2"]; -SELECT * FROM person WHERE tags CONTAINSSOME ["tag1", "tag2"]; --- Select all records where the `tags` does not contain "tag1" OR "tag2" -SELECT * FROM person WHERE tags ⊅ ["tag1", "tag2"]; -SELECT * FROM person WHERE tags CONTAINSNONE ["tag1", "tag2"]; - --- Select all records where all email address values end with 'gmail.com' -SELECT * FROM person WHERE emails.*.value = /gmail.com$/; --- Select all records where no email address values end with 'gmail.com' -SELECT * FROM person WHERE emails.*.value != /gmail.com$/; --- Select all records where any email address value ends with 'gmail.com' -SELECT * FROM person WHERE emails.*.value ?= /gmail.com$/; - --- Select all person records, and all of their likes -SELECT ->likes->? FROM person; --- Select all person records, and all of their friends -SELECT ->friend->person FROM person; --- Select all person records, and all of the friends and followers -SELECT <->(friend, follow)->person FROM person; --- Select all person records, and the ids of people who like each person -SELECT *, <-likes<-person.id FROM person; --- Select all person records, and the people who like this person, who are older than 18 -SELECT *, <-friend<-person[age>=18] AS friends FROM person; --- Select only person records where a friend likes chocolate -SELECT * FROM person WHERE ->friend->person->likes->food:chocolate; --- Select the products purchased by friends of a specific person record -SELECT ->friend->person{1..3}->purchased->product FROM @person:tobie; --- Select all 1st, 2nd, or 3rd level people who this specific person record knows -SELECT ->knows->?{1..3} FROM @person:tobie; --- Select all 1st, 2nd, and 3rd level people who this specific person record knows, or likes, as separet paths -SELECT ->knows->(? AS f1)->knows->(? AS f2)->(knows, likes AS e3 WHERE hot=true)->(? AS f3) FROM @person:tobie; --- Select all person records (and their recipients), who have sent more than 5 emails -SELECT *, ->sent->email->to->person FROM person WHERE count(->sent->email->to->person) > 5; --- Select all people who know jaime -SELECT * FROM person WHERE ->knows->@person:jaime; --- Select all person records, and all of the adult friends -SELECT ->knows->(person WHERE age >= 18) FROM person; --- Select other products purchased by people who purchased this laptop -SELECT <-purchased<-person->purchased->product FOLLOW DISTINCT FROM @product:laptop; --- Select products purchased by people who have purchased the same products that we have purchased -SELECT ->purchased->product<-purchased<-person->purchased->product FOLLOW DISTINCT FROM @person:tobie; --- Select products purchased by people in the last 3 weeks who have purchased the same products that we have purchased -SELECT ->purchased->product<-purchased<-person->(purchased WHERE created_at > now() - 3w)->product FOLLOW DISTINCT FROM @person:tobie; --- Select products purchased by people who have purchased the same products that we have purchased -SELECT ->purchased->product<-purchased<-person->purchased->product FOLLOW DISTINCT FROM @person:tobie; --- Select all people who have sent an email to tobie@abcum.com -SELECT * FROM person WHERE @email:{tobie@abcum.com}->from->email.address IN emails.?.value; -``` diff --git a/doc/SECURITY.md b/doc/SECURITY.md deleted file mode 100644 index 1a507b30..00000000 --- a/doc/SECURITY.md +++ /dev/null @@ -1,140 +0,0 @@ -# Security - -This document describes how authentication and user access works for accessing the database. - -#### Authentication levels - -** ROOT authentication ** - -- Signin with root email and password, set at server initialisation -- Can create, select, delete all namespaces -- Can create, select, delete all databases -- Can create, select, delete all tables -- Can create, select, delete all data -- Not restricted by any Table or Field permissions - -** NS authentcation ** - -- Signin with NS, email, and password, which must exist as a NAMESPACE USER -- Can create, select, delete any database under the NS -- Can create, select, delete any tables under the NS -- Can create, select, delete any data under the NS -- Not restricted by any Table or Field permissions - -** DB authentication ** - -- Signup -- Signin with NS, DB, email, and password, which must exist as a DATABASE USER -- Can create, select, delete any tables under the DB -- Can create, select, delete any data under the DB -- Not restricted by any Table or Field permissions - -** SC authentcation ** - -- Signup with NS, DB, SC, email, and password, which must successfully pass an scope SIGNUP clause -- Signin with NS, DB, SC, email, and password, which must successfully pass an scope SIGNIN clause -- Can create, select, delete any data under the DB, as long as permission match -- Restricted by any Table or Field permissions - -#### Database signup - -** SC signup ** - -- POST an HTTP FORM or JSON to /signin - - ```json - { - "NS": "abcum", - "DB": "acreon", - "SC": "account", - "user": "user@example.com", - "pass": "123456" - } - ``` - -- Receive a HTTP 200 code from server - -#### Database signin - -** ROOT signin ** - -- Use HTTP Basic Auth specifying username:password with each request - - ```HTTP - POST /sql HTTP/1.1 - Host: localhost:8000 - Content-Type: application/json - Authorization: Basic cm9vdDpyb290 - ``` - -** NS signin ** - -- POST an HTTP FORM or JSON to /signin - - ```json - { - "NS": "abcum", - "user": "user@example.com", - "pass": "123456" - } - ``` - -- Receive a JSON Web Token from the server - -- Use the JSON Web Token to authenticate requests - - ```HTTP - POST /sql HTTP/1.1 - Host: localhost:8000 - Content-Type: application/json - Authorization: Bearer eyJhbGciOiIkpXVCJ9.eyJEQiI6ImFiY30Nzk3Mzc2NDh9.RMVkex6OpHPZY1BQIQKlQ - ``` - -** DB signin ** - -- POST an HTTP FORM or JSON to /signin - - ```json - { - "NS": "abcum", - "DB": "acreon", - "user": "user@example.com", - "pass": "123456" - } - ``` - -- Receive a JSON Web Token from the server - -- Use the JSON Web Token to authenticate requests - - ```HTTP - POST /sql HTTP/1.1 - Host: localhost:8000 - Content-Type: application/json - Authorization: Bearer eyJhbGciOiIkpXVCJ9.eyJEQiI6ImFiY30Nzk3Mzc2NDh9.RMVkex6OpHPZY1BQIQKlQ - ``` - -** SC signin ** - -- POST an HTTP FORM or JSON to /signup - - ```json - { - "NS": "abcum", - "DB": "acreon", - "SC": "account", - "user": "user@example.com", - "pass": "123456" - } - ``` - -- Receive a JSON Web Token from the server - -- Use the JSON Web Token to authenticate requests - - ```HTTP - POST /sql HTTP/1.1 - Host: localhost:8000 - Content-Type: application/json - Authorization: Bearer eyJhbGciOiIkpXVCJ9.eyJEQiI6ImFiY30Nzk3Mzc2NDh9.RMVkex6OpHPZY1BQIQKlQ - ``` diff --git a/doc/STORAGE.md b/doc/STORAGE.md deleted file mode 100644 index d13cac66..00000000 --- a/doc/STORAGE.md +++ /dev/null @@ -1,93 +0,0 @@ -# Storage - -This document describes how the database data is stored in the key-value storage layer; - -**Base keys** - -```bash -{$kv} = "surreal" # This is the base key -``` - -The base key is used to separate the data used in SurrealDB from data used by other databases using the same key:value store. - -```bash -{$ns} = "acme" # This is the name of the namespace -``` - -The namespace key is used to enable separation of data and multi-tenancy of databases on SurrealDB. - -```bash -{$db} = "test" # This is the name of the database -``` - -The database key is used to separate data into multiple different databases under each multi-tenant installation. - -#### Chars - -Each data type is stored using a different symbol in the key-value pair. - -```bash -! # Used to store config data -* # Used to store item data -~ # Used to store item diffs -• # Used to store item trail -« # Used to store item edges -» # Used to store item edges -¤ # Used to store index data -``` - -#### Keys - -The keys for the data in the key-value store use the template below. - -```bash -KV /{$kv} -NS /{$kv}/{$ns} -NT /{$kv}/{$ns}/!/t/{$tk} -NU /{$kv}/{$ns}/!/u/{$us} -DB /{$kv}/{$ns}/*/{$db} -LV /{$kv}/{$ns}/*/{$db}/!/l/{$lv} -SC /{$kv}/{$ns}/*/{$db}/!/s/{$sc} -ST /{$kv}/{$ns}/*/{$db}/!/s/{$sc}/!/t/{$tk} -DT /{$kv}/{$ns}/*/{$db}/!/t/{$tk} -DU /{$kv}/{$ns}/*/{$db}/!/u/{$us} -VW /{$kv}/{$ns}/*/{$db}/!/v/{$vw} -TB /{$kv}/{$ns}/*/{$db}/*/{$tb} -EV /{$kv}/{$ns}/*/{$db}/*/{$tb}/!/e/{$ev} -FD /{$kv}/{$ns}/*/{$db}/*/{$tb}/!/f/{$fd} -IX /{$kv}/{$ns}/*/{$db}/*/{$tb}/!/i/{$ix} -Table /{$kv}/{$ns}/*/{$db}/*/{$tb}/* -Thing /{$kv}/{$ns}/*/{$db}/*/{$tb}/*/{$id} -Field /{$kv}/{$ns}/*/{$db}/*/{$tb}/*/{$id}/*/{$fd} -Edge /{$kv}/{$ns}/*/{$db}/*/{$tb}/*/{$id}/»/{$tp}/{$ft}/{$fk} -Patch /{$kv}/{$ns}/*/{$db}/*/{$tb}/~/{$id}/{$at} -Index /{$kv}/{$ns}/*/{$db}/*/{$tb}/¤/{$ix}/{$fd} -Point /{$kv}/{$ns}/*/{$db}/*/{$tb}/¤/{$ix}/{$fd}/{$id} -``` - -The specific keys listed above are displayed with example data below. - -```bash -KV /surreal -NS /surreal/abcum -NT /surreal/abcum/!/t/default -NU /surreal/abcum/!/u/tobie@abcum.com -DB /surreal/abcum/*/acreon -LV /surreal/abcum/*/acreon/!/l/name -SC /surreal/abcum/*/acreon/!/s/admin -ST /surreal/abcum/*/acreon/!/s/admin/!/t/default -DT /surreal/abcum/*/acreon/!/t/default -DU /surreal/abcum/*/acreon/!/u/tobie@abcum.com -VW /surreal/abcum/*/acreon/!/v/ages -TB /surreal/abcum/*/acreon/*/person -EV /surreal/abcum/*/acreon/*/person/!/e/activity -FD /surreal/abcum/*/acreon/*/person/!/f/name.first -IX /surreal/abcum/*/acreon/*/person/!/i/names -Table /surreal/abcum/*/acreon/*/person/* -Thing /surreal/abcum/*/acreon/*/person/*/tobie -Field /surreal/abcum/*/acreon/*/person/*/tobie/*/name.first -Edge /surreal/abcum/*/acreon/*/person/*/tobie/»/like/entity/apple -Patch /surreal/abcum/*/acreon/*/person/~/tobie/2016-01-29T22:42:56.478173947Z -Index /surreal/abcum/*/acreon/*/person/¤/names/[col1,col2,col3] -Point /surreal/abcum/*/acreon/*/person/¤/names/[col1,col2,col3]/tobie -``` diff --git a/go.mod b/go.mod deleted file mode 100644 index 5ffe539c..00000000 --- a/go.mod +++ /dev/null @@ -1,68 +0,0 @@ -module github.com/surrealdb/surrealdb - -go 1.17 - -require ( - cloud.google.com/go v0.99.0 - cloud.google.com/go/errorreporting v0.1.0 - cloud.google.com/go/logging v1.4.2 - github.com/dgraph-io/ristretto v0.1.0 - github.com/dgrijalva/jwt-go v3.2.0+incompatible - github.com/elithrar/simple-scrypt v1.3.0 - github.com/gorilla/websocket v1.4.2 - github.com/hjson/hjson-go v3.1.0+incompatible - github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d - github.com/pkg/profile v1.6.0 - github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be - github.com/rs/xid v1.3.0 - github.com/satori/go.uuid v1.2.0 - github.com/sergi/go-diff v1.2.0 - github.com/sirupsen/logrus v1.8.1 - github.com/smartystreets/goconvey v1.7.2 - github.com/spf13/cobra v1.2.1 - github.com/surrealdb/bump v0.0.0-20211208111645-b89bf4013dc9 - github.com/surrealdb/cork v0.0.0-20211208110447-54ccd49930c9 - github.com/surrealdb/fibre v0.0.0-20211208172721-cc4f2770111e - github.com/surrealdb/rixxdb v0.0.0-20211019142450-5b9e2a203f4c - github.com/ugorji/go/codec v1.2.6 - golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b - golang.org/x/net v0.0.0-20211209124913-491a49abca63 - golang.org/x/text v0.3.7 -) - -require ( - github.com/census-instrumentation/opencensus-proto v0.2.1 // indirect - github.com/cespare/xxhash v1.1.0 // indirect - github.com/cespare/xxhash/v2 v2.1.1 // indirect - github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403 // indirect - github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed // indirect - github.com/dustin/go-humanize v1.0.0 // indirect - github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0 // indirect - github.com/envoyproxy/protoc-gen-validate v0.1.0 // indirect - github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect - github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/google/go-cmp v0.5.6 // indirect - github.com/googleapis/gax-go/v2 v2.1.1 // indirect - github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 // indirect - github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jtolds/gls v4.20.0+incompatible // indirect - github.com/mattn/go-colorable v0.0.9 // indirect - github.com/mattn/go-isatty v0.0.3 // indirect - github.com/mitchellh/mapstructure v1.4.3 // indirect - github.com/ory/graceful v0.1.1 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/segmentio/ksuid v1.0.4 // indirect - github.com/smartystreets/assertions v1.2.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect - go.opencensus.io v0.23.0 // indirect - golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 // indirect - golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect - google.golang.org/api v0.61.0 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0 // indirect - google.golang.org/grpc v1.40.0 // indirect - google.golang.org/protobuf v1.27.1 // indirect -) diff --git a/go.sum b/go.sum deleted file mode 100644 index 4d50fb0e..00000000 --- a/go.sum +++ /dev/null @@ -1,756 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= -cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= -cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= -cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= -cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= -cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= -cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= -cloud.google.com/go v0.92.2/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= -cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= -cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= -cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= -cloud.google.com/go v0.99.0 h1:y/cM2iqGgGi5D5DQZl6D9STN/3dR/Vx5Mp8s752oJTY= -cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/errorreporting v0.1.0 h1:z40EhrjRspplwbpO+9DSnC4kgDokBi94T/gYwtdKL5Q= -cloud.google.com/go/errorreporting v0.1.0/go.mod h1:cZSiBMvrnl0X13pD9DwKf9sQ8Eqy3EzHqkyKBZxiIrM= -cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= -cloud.google.com/go/logging v1.4.2 h1:Mu2Q75VBDQlW1HlBMjTX4X84UFR73G1TiLlRYc/b7tA= -cloud.google.com/go/logging v1.4.2/go.mod h1:jco9QZSx8HiVVqLJReq7z7bVdj0P1Jb9PDFs63T+axo= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= -github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= -github.com/census-instrumentation/opencensus-proto v0.2.1 h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= -github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403 h1:cqQfy1jclcSy/FwLjemeg3SR1yaINm74aQyupQ0Bl8M= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed h1:OZmjad4L3H8ncOIR8rnb5MREYqG8ixi5+WbeUsquF0c= -github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgraph-io/ristretto v0.1.0 h1:Jv3CGQHp9OjuMBSne1485aDpUkTKEcUqF+jm/LuerPI= -github.com/dgraph-io/ristretto v0.1.0/go.mod h1:fux0lOrBhrVCJd3lcTHsIJhq1T2rokOu6v9Vcb3Q9ug= -github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/elithrar/simple-scrypt v1.3.0 h1:KIlOlxdoQf9JWKl5lMAJ28SY2URB0XTRDn2TckyzAZg= -github.com/elithrar/simple-scrypt v1.3.0/go.mod h1:U2XQRI95XHY0St410VE3UjT7vuKb1qPwrl/EJwEqnZo= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0 h1:dulLQAYQFYtG5MTplgNGHWuV2D+OBD+Z8lmDBmbLg+s= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= -github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= -github.com/googleapis/gax-go/v2 v2.1.1 h1:dp3bWCh+PPO1zjRRiCSczJav13sBvG4UhNyVTa1KqdU= -github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3SQ2HBHWsJUfbNBiTXJDeW2QDxw9AQ0= -github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= -github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= -github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= -github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/hjson/hjson-go v3.1.0+incompatible h1:DY/9yE8ey8Zv22bY+mHV1uk2yRy0h8tKhZ77hEdi0Aw= -github.com/hjson/hjson-go v3.1.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= -github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= -github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= -github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs= -github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/ory/graceful v0.1.1 h1:zx+8tDObLPrG+7Tc8jKYlXsqWnLtOQA1IZ/FAAKHMXU= -github.com/ory/graceful v0.1.1/go.mod h1:zqu70l95WrKHF4AZ6tXHvAqAvpY6M7g6ttaAVcMm7KU= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/profile v1.6.0 h1:hUDfIISABYI59DyeB3OTay/HxSRwTQ8rB/H83k6r5dM= -github.com/pkg/profile v1.6.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= -github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ= -github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rs/xid v1.3.0 h1:6NjYksEUlhurdVehpc7S7dk6DAmcKv8V9gG0FsVN2U4= -github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c= -github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE= -github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= -github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= -github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= -github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= -github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ= -github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= -github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/surrealdb/bump v0.0.0-20211208102305-88d509230106/go.mod h1:7j+Wcc4B4QM++XXvz8wCpFdSRWHvWLWMr7iC6495KoM= -github.com/surrealdb/bump v0.0.0-20211208111645-b89bf4013dc9 h1:6yfxCWaPVNeA32FOgZRIor6nT8FhGDbeDVaFNm/3ago= -github.com/surrealdb/bump v0.0.0-20211208111645-b89bf4013dc9/go.mod h1:7j+Wcc4B4QM++XXvz8wCpFdSRWHvWLWMr7iC6495KoM= -github.com/surrealdb/cork v0.0.0-20211208110447-54ccd49930c9 h1:DeURFsQG41ZtWL76+wvSeohgLY6vyvoeRLauhNhy/A4= -github.com/surrealdb/cork v0.0.0-20211208110447-54ccd49930c9/go.mod h1:q+YzNz7MWmUNiYkZNDXuOSrp2pdIXGLdmpVgf2pcoG4= -github.com/surrealdb/fibre v0.0.0-20211208172721-cc4f2770111e h1:HGhm81GyA+dSwhF6RY+mATAqB/vcMIC39UUw5DBcxCo= -github.com/surrealdb/fibre v0.0.0-20211208172721-cc4f2770111e/go.mod h1:p7ih2w2iYiJauQciUUW8YpdMXdba08FtNbW9Zi7KltA= -github.com/surrealdb/rixxdb v0.0.0-20211019142450-5b9e2a203f4c h1:btj+hGxS7X4qHqceTIkCCWhdIgkSuNe96ZLB2lPLEs0= -github.com/surrealdb/rixxdb v0.0.0-20211019142450-5b9e2a203f4c/go.mod h1:S4h2aMp3Lk62FXmhCOdS0OeWuiaNeP8Vk4OOXnGa0Cw= -github.com/ugorji/go v1.2.6 h1:tGiWC9HENWE2tqYycIqFTNorMmFRVhNwCpDOpWqnk8E= -github.com/ugorji/go v1.2.6/go.mod h1:anCg0y61KIhDlPZmnH+so+RQbysYVyDko0IMgJv0Nn0= -github.com/ugorji/go/codec v1.2.6 h1:7kbGefxLoDBuYXOms4yD7223OpNMMPNPZxXk5TvFcyQ= -github.com/ugorji/go/codec v1.2.6/go.mod h1:V6TCNZ4PHqoHGFZuSG1W8nrCzzdgA2DozYxWFFpvxTw= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= -go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= -go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= -go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= -go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= -go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b h1:QAqMVf3pSa6eeTsuklijukjXBlj7Es2QQplab+/RbQ4= -golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211209124913-491a49abca63 h1:iocB37TsdFuN6IBRZ+ry36wrkoV51/tl5vOWqkcPGvY= -golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 h1:RerP+noqYHUQ8CMRcPlC2nvTa4dcBIjegkuWdcUDuqg= -golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 h1:TyHqChC80pFkXWraUUf6RuB5IqFdQieMLwwCJokV2pc= -golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= -google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= -google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= -google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= -google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= -google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= -google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= -google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= -google.golang.org/api v0.55.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= -google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= -google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= -google.golang.org/api v0.61.0 h1:TXXKS1slM3b2bZNJwD5DV/Tp6/M2cLzLOLh9PjDhrw8= -google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= -google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= -google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= -google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= -google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= -google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= -google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= -google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= -google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= -google.golang.org/genproto v0.0.0-20210909211513-a8c4777a87af/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= -google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0 h1:c7yRRmuQiVMo+YppNj5MUREXUyc2lPo3DrtYMwaWQ28= -google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= -google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= -google.golang.org/grpc v1.40.0 h1:AGJ0Ih4mHjSeibYkFGh1dD9KJ/eOtZ93I6hoHhukQ5Q= -google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= -google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= -google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/kvs/db.go b/kvs/db.go deleted file mode 100644 index 98498982..00000000 --- a/kvs/db.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kvs - -import ( - "context" - "io" -) - -// DB represents a database implementation -type DB interface { - Begin(context.Context, bool) (TX, error) - Import(io.Reader) error - Export(io.Writer) error - Close() error -} diff --git a/kvs/ds.go b/kvs/ds.go deleted file mode 100644 index 487355b9..00000000 --- a/kvs/ds.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kvs - -import ( - "context" - "io" - "strings" - - "github.com/surrealdb/surrealdb/cnf" -) - -// DB represents a backing datastore. -type DS struct { - db DB -} - -// New sets up the underlying key-value store -func New(opts *cnf.Options) (ds *DS, err error) { - - var db DB - - switch { - case opts.DB.Path == "memory": - db, err = stores["rixxdb"](opts) - case strings.HasPrefix(opts.DB.Path, "file://"): - db, err = stores["rixxdb"](opts) - case strings.HasPrefix(opts.DB.Path, "dendrodb://"): - db, err = stores["dendro"](opts) - } - - if err != nil { - return - } - - ds = &DS{db: db} - - return - -} - -// Begin begins a new read / write transaction -// with the underlying database, and returns -// the transaction, or any error which occured. -func (ds *DS) Begin(ctx context.Context, writable bool) (txn TX, err error) { - return ds.db.Begin(ctx, writable) -} - -// Import loads database operations from a reader. -// This can be used to playback a database snapshot -// into an already running database. -func (ds *DS) Import(r io.Reader) (err error) { - return ds.db.Import(r) -} - -// Export saves all database operations to a writer. -// This can be used to save a database snapshot -// to a secondary file or stream. -func (ds *DS) Export(w io.Writer) (err error) { - return ds.db.Export(w) -} - -// Close closes the underlying rixxdb / dendrodb -// database connection, enabling the underlying -// database to clean up remainging transactions. -func (ds *DS) Close() (err error) { - return ds.db.Close() -} diff --git a/kvs/err.go b/kvs/err.go deleted file mode 100644 index 1e003f9e..00000000 --- a/kvs/err.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kvs - -import "fmt" - -// DBError is an error which occurs when there is a -// problem with writing keys/values to the database. -type DBError struct { - Err error -} - -// Error returns the string representation of the error. -func (e *DBError) Error() string { - return fmt.Sprintf("Unable to write to the database: %s", e.Err) -} diff --git a/kvs/kv.go b/kvs/kv.go deleted file mode 100644 index 68ee4eae..00000000 --- a/kvs/kv.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kvs - -// KV represents a database item -type KV interface { - Exi() bool - Key() []byte - Val() []byte - Ver() uint64 -} diff --git a/kvs/main.go b/kvs/main.go deleted file mode 100644 index 2e49c30c..00000000 --- a/kvs/main.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kvs - -import ( - "context" - "io" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/log" -) - -var ds *DS - -// Stores the different backend implementations -var stores = make(map[string]func(*cnf.Options) (DB, error)) - -// Setup sets up the connection with the data layer -func Setup(opts *cnf.Options) (err error) { - log.WithPrefix("kvs").Infof("Starting kvs storage at %s", opts.DB.Path) - ds, err = New(opts) - log.WithPrefix("kvs").Infof("Started kvs storage at %s", opts.DB.Path) - return -} - -// Exit shuts down the connection with the data layer -func Exit(opts *cnf.Options) (err error) { - log.WithPrefix("kvs").Infof("Shutting down kvs storage at %s", opts.DB.Path) - return ds.Close() -} - -// Begin begins a new read / write transaction -// with the underlying database, and returns -// the transaction, or any error which occured. -func Begin(ctx context.Context, writable bool) (txn TX, err error) { - return ds.db.Begin(ctx, writable) -} - -// Import loads database operations from a reader. -// This can be used to playback a database snapshot -// into an already running database. -func Import(r io.Reader) (err error) { - return ds.db.Import(r) -} - -// Export saves all database operations to a writer. -// This can be used to save a database snapshot -// to a secondary file or stream. -func Export(w io.Writer) (err error) { - return ds.db.Export(w) -} - -// Close closes the underlying rixxdb / dendrodb -// database connection, enabling the underlying -// database to clean up remainging transactions. -func Close() (err error) { - return ds.db.Close() -} - -// Register registers a new database type with -// the kvs package, enabling it's use as a -// backing datastore within SurrealDB. -func Register(name string, constructor func(*cnf.Options) (DB, error)) { - stores[name] = constructor -} diff --git a/kvs/rixxdb/db.go b/kvs/rixxdb/db.go deleted file mode 100644 index e48a6e22..00000000 --- a/kvs/rixxdb/db.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rixxdb - -import ( - "io" - - "context" - - "github.com/surrealdb/rixxdb" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/log" -) - -type DB struct { - pntr *rixxdb.DB -} - -func (db *DB) Begin(ctx context.Context, writable bool) (txn kvs.TX, err error) { - var pntr *rixxdb.TX - if pntr, err = db.pntr.Begin(writable); err != nil { - log.WithPrefix("kvs").Errorln(err) - err = &kvs.DBError{Err: err} - return - } - return &TX{pntr: pntr}, err -} - -func (db *DB) Import(r io.Reader) (err error) { - return db.pntr.Load(r) -} - -func (db *DB) Export(w io.Writer) (err error) { - return db.pntr.Save(w) -} - -func (db *DB) Close() (err error) { - return db.pntr.Close() -} diff --git a/kvs/rixxdb/main.go b/kvs/rixxdb/main.go deleted file mode 100644 index a77741c3..00000000 --- a/kvs/rixxdb/main.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rixxdb - -import ( - "github.com/surrealdb/rixxdb" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/log" -) - -func init() { - - kvs.Register("rixxdb", func(opts *cnf.Options) (db kvs.DB, err error) { - - var pntr *rixxdb.DB - - pntr, err = rixxdb.Open(opts.DB.Path, &rixxdb.Config{ - // Explicitly sync writes - SyncWrites: true, - // Set the encryption key - EncryptionKey: opts.DB.Key, - // Set the sync offset duration - FlushPolicy: opts.DB.Proc.Flush, - // Set the shrink offset duration - ShrinkPolicy: opts.DB.Proc.Shrink, - }) - - if err != nil { - log.WithPrefix("kvs").Errorln(err) - return - } - - return &DB{pntr: pntr}, err - - }) - -} diff --git a/kvs/rixxdb/tx.go b/kvs/rixxdb/tx.go deleted file mode 100644 index 1b3260b4..00000000 --- a/kvs/rixxdb/tx.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rixxdb - -import ( - "context" - - "github.com/surrealdb/rixxdb" - "github.com/surrealdb/surrealdb/kvs" -) - -type TX struct { - pntr *rixxdb.TX -} - -func one(res *rixxdb.KV, err error) (kvs.KV, error) { - - if err != nil { - return nil, &kvs.DBError{Err: err} - } - - return res, err - -} - -func many(res []*rixxdb.KV, err error) ([]kvs.KV, error) { - - if err != nil { - return nil, &kvs.DBError{Err: err} - } - - var out = make([]kvs.KV, len(res)) - - for i, v := range res { - out[i] = v - } - - return out, err - -} - -func (tx *TX) Closed() bool { - return tx.pntr.Closed() -} - -func (tx *TX) Cancel() error { - return tx.pntr.Cancel() -} - -func (tx *TX) Commit() error { - return tx.pntr.Commit() -} - -func (tx *TX) All(ctx context.Context, key []byte) ([]kvs.KV, error) { - res, err := tx.pntr.All(key) - return many(res, err) -} - -func (tx *TX) AllP(ctx context.Context, key []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.AllP(key, max) - return many(res, err) -} - -func (tx *TX) AllR(ctx context.Context, beg []byte, end []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.AllR(beg, end, max) - return many(res, err) -} - -func (tx *TX) Clr(ctx context.Context, key []byte) (kvs.KV, error) { - res, err := tx.pntr.Clr(key) - return one(res, err) -} - -func (tx *TX) ClrP(ctx context.Context, key []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.ClrP(key, max) - return many(res, err) -} - -func (tx *TX) ClrR(ctx context.Context, beg []byte, end []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.ClrR(beg, end, max) - return many(res, err) -} - -func (tx *TX) Get(ctx context.Context, ver int64, key []byte) (kvs.KV, error) { - res, err := tx.pntr.Get(uint64(ver), key) - return one(res, err) -} - -func (tx *TX) GetP(ctx context.Context, ver int64, key []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.GetP(uint64(ver), key, max) - return many(res, err) -} - -func (tx *TX) GetR(ctx context.Context, ver int64, beg []byte, end []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.GetR(uint64(ver), beg, end, max) - return many(res, err) -} - -func (tx *TX) Del(ctx context.Context, ver int64, key []byte) (kvs.KV, error) { - res, err := tx.pntr.Del(uint64(ver), key) - return one(res, err) -} - -func (tx *TX) DelC(ctx context.Context, ver int64, key []byte, exp []byte) (kvs.KV, error) { - res, err := tx.pntr.DelC(uint64(ver), key, exp) - return one(res, err) -} - -func (tx *TX) DelP(ctx context.Context, ver int64, key []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.DelP(uint64(ver), key, max) - return many(res, err) -} - -func (tx *TX) DelR(ctx context.Context, ver int64, beg []byte, end []byte, max uint64) ([]kvs.KV, error) { - res, err := tx.pntr.DelR(uint64(ver), beg, end, max) - return many(res, err) -} - -func (tx *TX) Put(ctx context.Context, ver int64, key []byte, val []byte) (kvs.KV, error) { - res, err := tx.pntr.Put(uint64(ver), key, val) - return one(res, err) -} - -func (tx *TX) PutC(ctx context.Context, ver int64, key []byte, val []byte, exp []byte) (kvs.KV, error) { - res, err := tx.pntr.PutC(uint64(ver), key, val, exp) - return one(res, err) -} diff --git a/kvs/tx.go b/kvs/tx.go deleted file mode 100644 index 8bb7539f..00000000 --- a/kvs/tx.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kvs - -import "context" - -// TX represents a database transaction -type TX interface { - Closed() bool - Cancel() error - Commit() error - - All(context.Context, []byte) ([]KV, error) - AllP(context.Context, []byte, uint64) ([]KV, error) - AllR(context.Context, []byte, []byte, uint64) ([]KV, error) - - Clr(context.Context, []byte) (KV, error) - ClrP(context.Context, []byte, uint64) ([]KV, error) - ClrR(context.Context, []byte, []byte, uint64) ([]KV, error) - - Put(context.Context, int64, []byte, []byte) (KV, error) - PutC(context.Context, int64, []byte, []byte, []byte) (KV, error) - - Get(context.Context, int64, []byte) (KV, error) - GetP(context.Context, int64, []byte, uint64) ([]KV, error) - GetR(context.Context, int64, []byte, []byte, uint64) ([]KV, error) - - Del(context.Context, int64, []byte) (KV, error) - DelC(context.Context, int64, []byte, []byte) (KV, error) - DelP(context.Context, int64, []byte, uint64) ([]KV, error) - DelR(context.Context, int64, []byte, []byte, uint64) ([]KV, error) -} diff --git a/log/hook.go b/log/hook.go deleted file mode 100644 index e4e52adb..00000000 --- a/log/hook.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "io" - "io/ioutil" - "os" - "time" - - "github.com/sirupsen/logrus" -) - -type DefaultHook struct { - w io.Writer - l []logrus.Level - f logrus.Formatter -} - -func (h *DefaultHook) Levels() []logrus.Level { - return h.l -} - -func (h *DefaultHook) Fire(entry *logrus.Entry) error { - bit, err := h.f.Format(entry) - if err != nil { - return err - } - _, err = h.w.Write(bit) - return err -} - -// SetLevel sets the logging level of the logger instance. -func (h *DefaultHook) SetLevel(v string) { - switch v { - case "trace": - h.l = TraceLevels - case "debug": - h.l = DebugLevels - case "info": - h.l = InfoLevels - case "warn": - h.l = WarnLevels - case "error": - h.l = ErrorLevels - case "fatal": - h.l = FatalLevels - case "panic": - h.l = PanicLevels - } -} - -// SetOutput sets the logging output of the logger instance. -func (h *DefaultHook) SetOutput(v string) { - switch v { - case "none": - h.w = ioutil.Discard - case "stdout": - h.w = os.Stdout - case "stderr": - h.w = os.Stderr - } -} - -// SetFormat sets the logging format of the logger instance. -func (h *DefaultHook) SetFormat(v string) { - switch v { - case "json": - h.f = &JSONFormatter{ - IgnoreFields: []string{ - "ctx", - "span", - "trace", - "fibre", - "prefix", - }, - TimestampFormat: time.RFC3339, - } - case "text": - h.f = &TextFormatter{ - IgnoreFields: []string{ - "ctx", - "vars", - "span", - "trace", - "fibre", - "prefix", - }, - TimestampFormat: time.RFC3339, - } - } -} diff --git a/log/json.go b/log/json.go deleted file mode 100644 index 3cb10537..00000000 --- a/log/json.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "time" - - "encoding/json" - - "github.com/sirupsen/logrus" -) - -type JSONFormatter struct { - IgnoreFields []string - TimestampFormat string -} - -func (f *JSONFormatter) ignore(field string) bool { - for _, ignore := range f.IgnoreFields { - if field == ignore { - return true - } - } - return false -} - -func (f *JSONFormatter) include(field string) bool { - for _, ignore := range f.IgnoreFields { - if field == ignore { - return false - } - } - return true -} - -func (f *JSONFormatter) Format(entry *logrus.Entry) (data []byte, err error) { - - if f.TimestampFormat == "" { - f.TimestampFormat = time.RFC3339Nano - } - - obj := make(map[string]interface{}) - - obj["msg"] = entry.Message - obj["time"] = entry.Time.Format(f.TimestampFormat) - obj["level"] = entry.Level.String() - - for k, v := range entry.Data { - if f.include(k) { - switch x := v.(type) { - case error: - obj[k] = x.Error() - default: - obj[k] = x - } - } - } - - data, err = json.Marshal(obj) - if err != nil { - return nil, err - } - - return append(data, '\n'), nil - -} diff --git a/log/log.go b/log/log.go deleted file mode 100644 index 9e42483e..00000000 --- a/log/log.go +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "fmt" - "io/ioutil" - "os" - "time" - - "github.com/sirupsen/logrus" -) - -const ( - PanicLevel = logrus.PanicLevel - FatalLevel = logrus.FatalLevel - ErrorLevel = logrus.ErrorLevel - WarnLevel = logrus.WarnLevel - InfoLevel = logrus.InfoLevel - DebugLevel = logrus.DebugLevel - TraceLevel = logrus.TraceLevel -) - -var ( - PanicLevels = []logrus.Level{ - PanicLevel, - } - FatalLevels = []logrus.Level{ - PanicLevel, - FatalLevel, - } - ErrorLevels = []logrus.Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - } - WarnLevels = []logrus.Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - } - InfoLevels = []logrus.Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - } - DebugLevels = []logrus.Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, - } - TraceLevels = []logrus.Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, - TraceLevel, - } -) - -var log *Logger - -// Logger ... -type Logger struct { - *logrus.Logger -} - -func init() { - log = &Logger{ - logrus.New(), - } -} - -// Instance returns the underlying logger instance -func Instance() *logrus.Logger { - return log.Logger -} - -// Hook adds a logging hook to the logger instance -func Hook(hook logrus.Hook) { - log.AddHook(hook) -} - -// IsPanic returns whether panic level logs are enabled -func IsPanic() bool { - return log.IsLevelEnabled(PanicLevel) -} - -// IsFatal returns whether fatal level logs are enabled -func IsFatal() bool { - return log.IsLevelEnabled(FatalLevel) -} - -// IsError returns whether error level logs are enabled -func IsError() bool { - return log.IsLevelEnabled(ErrorLevel) -} - -// IsWarn returns whether warning level logs are enabled -func IsWarn() bool { - return log.IsLevelEnabled(WarnLevel) -} - -// IsInfo returns whether info level logs are enabled -func IsInfo() bool { - return log.IsLevelEnabled(InfoLevel) -} - -// IsDebug returns whether debug level logs are enabled -func IsDebug() bool { - return log.IsLevelEnabled(DebugLevel) -} - -// IsTrace returns whether trace level logs are enabled -func IsTrace() bool { - return log.IsLevelEnabled(TraceLevel) -} - -// SetLevel sets the logging level of the logger instance. -func SetLevel(v string) { - switch v { - case "trace": - log.Logger.SetLevel(TraceLevel) - case "debug": - log.Logger.SetLevel(DebugLevel) - case "info": - log.Logger.SetLevel(InfoLevel) - case "warn": - log.Logger.SetLevel(WarnLevel) - case "error": - log.Logger.SetLevel(ErrorLevel) - case "fatal": - log.Logger.SetLevel(FatalLevel) - case "panic": - log.Logger.SetLevel(PanicLevel) - } -} - -// SetOutput sets the logging output of the logger instance. -func SetOutput(v string) { - switch v { - case "none": - log.Logger.SetOutput(ioutil.Discard) - case "stdout": - log.Logger.SetOutput(os.Stdout) - case "stderr": - log.Logger.SetOutput(os.Stderr) - case "stackdriver": - log.Logger.SetOutput(ioutil.Discard) - log.Logger.AddHook(NewStackDriver()) - } -} - -// SetFormat sets the logging format of the logger instance. -func SetFormat(v string) { - switch v { - case "json": - log.Logger.SetFormatter(&JSONFormatter{ - IgnoreFields: []string{ - "ctx", - "span", - "trace", - "fibre", - "prefix", - }, - TimestampFormat: time.RFC3339, - }) - case "text": - log.Logger.SetFormatter(&TextFormatter{ - IgnoreFields: []string{ - "ctx", - "vars", - "span", - "trace", - "fibre", - "prefix", - }, - TimestampFormat: time.RFC3339, - }) - } -} - -func Display(v ...interface{}) { - if isTerminal { - fmt.Print(v...) - } -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(v ...interface{}) { - log.Debug(v...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, v ...interface{}) { - log.Debugf(format, v...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(v ...interface{}) { - log.Debugln(v...) -} - -// Error loggs a message at level Error on the standard logger. -func Error(v ...interface{}) { - log.Error(v...) -} - -// Errorf loggs a message at level Error on the standard logger. -func Errorf(format string, v ...interface{}) { - log.Errorf(format, v...) -} - -// Errorln loggs a message at level Error on the standard logger. -func Errorln(v ...interface{}) { - log.Errorln(v...) -} - -// Fatal loggs a message at level Fatal on the standard logger. -func Fatal(v ...interface{}) { - log.Fatal(v...) -} - -// Fatalf loggs a message at level Fatal on the standard logger. -func Fatalf(format string, v ...interface{}) { - log.Fatalf(format, v...) -} - -// Fatalln loggs a message at level Fatal on the standard logger. -func Fatalln(v ...interface{}) { - log.Fatalln(v...) -} - -// Info loggs a message at level Info on the standard logger. -func Info(v ...interface{}) { - log.Info(v...) -} - -// Infof loggs a message at level Info on the standard logger. -func Infof(format string, v ...interface{}) { - log.Infof(format, v...) -} - -// Infoln loggs a message at level Info on the standard logger. -func Infoln(v ...interface{}) { - log.Infoln(v...) -} - -// Panic loggs a message at level Panic on the standard logger. -func Panic(v ...interface{}) { - log.Panic(v...) -} - -// Panicf loggs a message at level Panic on the standard logger. -func Panicf(format string, v ...interface{}) { - log.Panicf(format, v...) -} - -// Panicln loggs a message at level Panic on the standard logger. -func Panicln(v ...interface{}) { - log.Panicln(v...) -} - -// Print loggs a message at level Print on the standard logger. -func Print(v ...interface{}) { - log.Print(v...) -} - -// Printf loggs a message at level Print on the standard logger. -func Printf(format string, v ...interface{}) { - log.Printf(format, v...) -} - -// Println loggs a message at level Print on the standard logger. -func Println(v ...interface{}) { - log.Println(v...) -} - -// Warn loggs a message at level Warn on the standard logger. -func Warn(v ...interface{}) { - log.Warn(v...) -} - -// Warnf loggs a message at level Warn on the standard logger. -func Warnf(format string, v ...interface{}) { - log.Warnf(format, v...) -} - -// Warnln loggs a message at level Warn on the standard logger. -func Warnln(v ...interface{}) { - log.Warnln(v...) -} - -// WithPrefix prepares a log entry with a prefix. -func WithPrefix(value interface{}) *logrus.Entry { - return log.WithField("prefix", value) -} - -// WithField prepares a log entry with a single data field. -func WithField(key string, value interface{}) *logrus.Entry { - return log.WithField(key, value) -} - -// WithFields prepares a log entry with multiple data fields. -func WithFields(fields map[string]interface{}) *logrus.Entry { - return log.WithFields(fields) -} diff --git a/log/stackdriver.go b/log/stackdriver.go deleted file mode 100644 index 4000b7e1..00000000 --- a/log/stackdriver.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "context" - "fmt" - "net/http" - "os" - "time" - - "github.com/surrealdb/fibre" - - "github.com/sirupsen/logrus" - - "github.com/surrealdb/surrealdb/util/build" - - "cloud.google.com/go/compute/metadata" - "cloud.google.com/go/errorreporting" - "cloud.google.com/go/logging" -) - -var proj = os.Getenv("PROJECT") - -type StackdriverLogger struct { - name string - client *logging.Client - logger *logging.Logger - errors *errorreporting.Client -} - -func NewStackDriver() *StackdriverLogger { - - var err error - - ctx := context.Background() - - hook := new(StackdriverLogger) - - conf := errorreporting.Config{ - ServiceName: "surreal", - ServiceVersion: build.GetInfo().Ver, - } - - // If no project id has been set - // then attempt to pull this from - // machine metadata if on GCE. - - if len(proj) == 0 { - if proj, err = metadata.ProjectID(); err != nil { - log.Fatalf("Failed to connect to Stackdriver: %v", err) - } - } - - // Connect to Stackdriver logging - // using the project name retrieved - // from the machine metadata. - - hook.client, err = logging.NewClient(ctx, proj) - if err != nil { - log.Fatalf("Failed to connect to Stackdriver: %v", err) - } - - // Connect to Stackdriver errors - // using the project name retrieved - // from the machine metadata. - - hook.errors, err = errorreporting.NewClient(ctx, proj, conf) - if err != nil { - log.Fatalf("Failed to connect to Stackdriver: %v", err) - } - - // Attempt to ping the Stackdriver - // endpoint to ensure the settings - // and authentication are correct. - - err = hook.client.Ping(ctx) - if err != nil { - log.Fatalf("Failed to connect to Stackdriver: %v", err) - } - - hook.logger = hook.client.Logger("surreal") - - return hook - -} - -func (h *StackdriverLogger) Levels() []logrus.Level { - switch log.GetLevel() { - case TraceLevel: - return TraceLevels - case DebugLevel: - return DebugLevels - case InfoLevel: - return InfoLevels - case WarnLevel: - return WarnLevels - case ErrorLevel: - return ErrorLevels - case FatalLevel: - return FatalLevels - case PanicLevel: - return PanicLevels - default: - return DebugLevels - } -} - -func (h *StackdriverLogger) Fire(entry *logrus.Entry) error { - - // If we receive an error, fatal, or - // panic - then log the error to GCE - // with a full stack trace. - - if entry.Level <= logrus.ErrorLevel { - - e := errorreporting.Entry{ - Error: fmt.Errorf("%s", entry.Message), - } - - for _, v := range entry.Data { - switch i := v.(type) { - case *http.Request: - e.Req = i - case *fibre.Context: - e.Req = i.Request().Request - } - } - - h.errors.Report(e) - - } - - // Otherwise just log the entry to - // Stackdriver, and attach any http - // request data to it if available. - - e := logging.Entry{ - Timestamp: entry.Time, - Labels: make(map[string]string, len(entry.Data)), - Payload: entry.Message, - Severity: logging.ParseSeverity(entry.Level.String()), - } - - if v, ok := entry.Data["trace"].(string); ok { - e.Trace = fmt.Sprintf("projects/%s/traces/%s", proj, v) - } - - if v, ok := entry.Data["span"].(string); ok { - e.SpanID = v - } - - if p, ok := entry.Data["prefix"]; ok && p == "sql" { - e.Payload = map[string]interface{}{ - "sql": entry.Message, - "vars": entry.Data["vars"], - } - } - - for k, v := range entry.Data { - switch i := v.(type) { - default: - e.Labels[k] = fmt.Sprintf("%v", i) - case *http.Request: - e.HTTPRequest = &logging.HTTPRequest{ - Request: i, - RemoteIP: i.RemoteAddr, - } - case *fibre.Context: - e.HTTPRequest = &logging.HTTPRequest{ - RemoteIP: i.IP().String(), - Request: i.Request().Request, - Status: i.Response().Status(), - RequestSize: i.Request().Size(), - ResponseSize: i.Response().Size(), - Latency: time.Since(i.Request().Start()), - } - } - } - - h.logger.Log(e) - - return nil - -} diff --git a/log/text.go b/log/text.go deleted file mode 100644 index be4d74b6..00000000 --- a/log/text.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "bytes" - "fmt" - "sort" - "strings" - "time" - - "github.com/mgutz/ansi" - - "github.com/sirupsen/logrus" -) - -const clear = ansi.Reset - -type TextFormatter struct { - IgnoreFields []string - TimestampFormat string -} - -func (f *TextFormatter) ignore(field string) bool { - for _, ignore := range f.IgnoreFields { - if field == ignore { - return true - } - } - return false -} - -func (f *TextFormatter) include(field string) bool { - for _, ignore := range f.IgnoreFields { - if field == ignore { - return false - } - } - return true -} - -func (f *TextFormatter) Format(entry *logrus.Entry) ([]byte, error) { - - if f.TimestampFormat == "" { - f.TimestampFormat = time.RFC3339Nano - } - - var keys []string = make([]string, 0) - - for k := range entry.Data { - if f.include(k) { - keys = append(keys, k) - } - } - - sort.Strings(keys) - - b := &bytes.Buffer{} - - switch isColoured { - case false: - f.printBasic(b, entry, keys) - case true: - f.printColored(b, entry, keys) - } - - b.WriteByte('\n') - - return b.Bytes(), nil - -} - -func (f *TextFormatter) printField(b *bytes.Buffer, key string, value interface{}) { - b.WriteString(key) - b.WriteByte('=') - - switch value := value.(type) { - case string: - if needsQuoting(value) { - b.WriteString(value) - } else { - fmt.Fprintf(b, "%q", value) - } - case error: - errmsg := value.Error() - if needsQuoting(errmsg) { - b.WriteString(errmsg) - } else { - fmt.Fprintf(b, "%q", value) - } - default: - fmt.Fprint(b, value) - } - - b.WriteByte(' ') -} - -func (f *TextFormatter) printBasic(b *bytes.Buffer, entry *logrus.Entry, keys []string) { - - f.printField(b, "time", entry.Time.Format(f.TimestampFormat)) - f.printField(b, "level", entry.Level.String()) - f.printField(b, "msg", entry.Message) - for _, key := range keys { - f.printField(b, key, entry.Data[key]) - } - -} - -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys []string) { - - var color string - var prefix string - - switch entry.Level { - case logrus.TraceLevel: - color = ansi.White - case logrus.DebugLevel: - color = ansi.Magenta - case logrus.InfoLevel: - color = ansi.Blue - case logrus.WarnLevel: - color = ansi.Yellow - case logrus.ErrorLevel: - color = ansi.Red - case logrus.FatalLevel: - color = ansi.Red - case logrus.PanicLevel: - color = ansi.Red - default: - color = ansi.Blue - } - - level := strings.ToUpper(entry.Level.String())[0:4] - - if value, ok := entry.Data["prefix"]; ok { - prefix = fmt.Sprint(" ", ansi.Cyan, value, ":", clear) - } - - fmt.Fprintf(b, "%s[%s]%s %s%+5s%s%s %s", ansi.LightBlack, entry.Time.Format(f.TimestampFormat), clear, color, level, clear, prefix, entry.Message) - - for _, k := range keys { - fmt.Fprintf(b, " %s%s%s=%+v", color, k, clear, entry.Data[k]) - } - -} - -func needsQuoting(text string) bool { - for _, ch := range text { - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.') { - return false - } - } - return true -} diff --git a/log/tty.go b/log/tty.go deleted file mode 100644 index 1ef58a98..00000000 --- a/log/tty.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "os" - "runtime" - - "golang.org/x/crypto/ssh/terminal" -) - -var ( - isTerminal bool - isColoured bool -) - -func init() { - isTerminal = terminal.IsTerminal(int(os.Stdout.Fd())) - isColoured = isTerminal && (runtime.GOOS != "windows") -} diff --git a/log/vars.go b/log/vars.go deleted file mode 100644 index 9f08d068..00000000 --- a/log/vars.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -const name = "surreal" diff --git a/main.go b/main.go deleted file mode 100644 index 108be2ff..00000000 --- a/main.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package main - -import ( - "os" - - "runtime" - - "github.com/pkg/profile" - - "github.com/surrealdb/surrealdb/cli" -) - -func main() { - - switch os.Getenv("DEBUG") { - case "cpu": - defer profile.Start(profile.CPUProfile, profile.ProfilePath("."), profile.NoShutdownHook).Stop() - case "mem": - defer profile.Start(profile.MemProfile, profile.ProfilePath("."), profile.NoShutdownHook).Stop() - case "block": - defer profile.Start(profile.BlockProfile, profile.ProfilePath("."), profile.NoShutdownHook).Stop() - } - - runtime.GOMAXPROCS(runtime.NumCPU()) - - cli.Init() - -} diff --git a/sql/ast.gen.go b/sql/ast.gen.go deleted file mode 100644 index a653ab7b..00000000 --- a/sql/ast.gen.go +++ /dev/null @@ -1,17360 +0,0 @@ -//go:build go1.6 -// +build go1.6 - -// Code generated by codecgen - DO NOT EDIT. - -package sql - -import ( - "errors" - codec1978 "github.com/ugorji/go/codec" - pkg1_language "golang.org/x/text/language" - "runtime" - "strconv" - "time" -) - -const ( - // ----- content types ---- - codecSelferCcUTF86263 = 1 - codecSelferCcRAW6263 = 255 - // ----- value types used ---- - codecSelferValueTypeArray6263 = 10 - codecSelferValueTypeMap6263 = 9 - codecSelferValueTypeString6263 = 6 - codecSelferValueTypeInt6263 = 2 - codecSelferValueTypeUint6263 = 3 - codecSelferValueTypeFloat6263 = 4 - codecSelferValueTypeNil6263 = 1 - codecSelferBitsize6263 = uint8(32 << (^uint(0) >> 63)) - codecSelferDecContainerLenNil6263 = -2147483648 -) - -var ( - errCodecSelferOnlyMapOrArrayEncodeToStruct6263 = errors.New(`only encoded map or array can be decoded into a struct`) -) - -type codecSelfer6263 struct{} - -func codecSelfer6263False() bool { return false } -func codecSelfer6263True() bool { return true } - -func init() { - if codec1978.GenVersion != 25 { - _, file, _, _ := runtime.Caller(0) - ver := strconv.FormatInt(int64(codec1978.GenVersion), 10) - panic(errors.New("codecgen version mismatch: current: 25, need " + ver + ". Re-generate file: " + file)) - } - if false { // reference the types, but skip this branch at build/run time - var _ pkg1_language.Tag - var _ time.Duration - } -} - -func (Query) codecSelferViaCodecgen() {} -func (x *Query) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Statements); yyxt4 != nil { - z.EncExtension(x.Statements, yyxt4) - } else { - x.Statements.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Statements\"") - } else { - r.EncodeString(`Statements`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Statements); yyxt5 != nil { - z.EncExtension(x.Statements, yyxt5) - } else { - x.Statements.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *Query) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Query{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Query) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Statements": - if yyxt5 := z.Extension(x.Statements); yyxt5 != nil { - z.DecExtension(&x.Statements, yyxt5) - } else { - x.Statements.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Query) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Statements); yyxt8 != nil { - z.DecExtension(&x.Statements, yyxt8) - } else { - x.Statements.CodecDecodeSelf(d) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *Query) IsCodecEmpty() bool { - return !(len(x.Statements) != 0 || false) -} - -func (Statements) codecSelferViaCodecgen() {} -func (x Statements) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encStatements((Statements)(x), e) - } // end block: if x slice == nil -} - -func (x *Statements) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decStatements((*Statements)(x), d) -} - -func (UseStatement) codecSelferViaCodecgen() {} -func (x *UseStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeString(string(x.NS)) - z.EncWriteArrayElem() - r.EncodeString(string(x.DB)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"NS\"") - } else { - r.EncodeString(`NS`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.NS)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"DB\"") - } else { - r.EncodeString(`DB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.DB)) - z.EncWriteMapEnd() - } - } -} - -func (x *UseStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = UseStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *UseStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "NS": - x.NS = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "DB": - x.DB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *UseStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.NS = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.DB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *UseStatement) IsCodecEmpty() bool { - return !(x.NS != "" || x.DB != "" || false) -} - -func (OptStatement) codecSelferViaCodecgen() {} -func (x *OptStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeString(string(x.Name)) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.What)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Name)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.What)) - z.EncWriteMapEnd() - } - } -} - -func (x *OptStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = OptStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *OptStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - x.Name = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "What": - x.What = (bool)(r.DecodeBool()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *OptStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Name = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.What = (bool)(r.DecodeBool()) - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *OptStatement) IsCodecEmpty() bool { - return !(x.Name != "" || bool(x.What) || false) -} - -func (BeginStatement) codecSelferViaCodecgen() {} -func (x *BeginStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *BeginStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = BeginStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *BeginStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *BeginStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *BeginStatement) IsCodecEmpty() bool { - return !(false) -} - -func (CancelStatement) codecSelferViaCodecgen() {} -func (x *CancelStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *CancelStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = CancelStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *CancelStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *CancelStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *CancelStatement) IsCodecEmpty() bool { - return !(false) -} - -func (CommitStatement) codecSelferViaCodecgen() {} -func (x *CommitStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *CommitStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = CommitStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *CommitStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *CommitStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *CommitStatement) IsCodecEmpty() bool { - return !(false) -} - -func (InfoStatement) codecSelferViaCodecgen() {} -func (x *InfoStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.What == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.EncExtension(x.Kind, yyxt5) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Kind\"") - } else { - r.EncodeString(`Kind`) - } - z.EncWriteMapElemValue() - if yyxt7 := z.Extension(x.Kind); yyxt7 != nil { - z.EncExtension(x.Kind, yyxt7) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *InfoStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = InfoStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *InfoStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Kind": - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.DecExtension(&x.Kind, yyxt5) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "What": - if r.TryNil() { - if x.What != nil { // remove the if-true - x.What = nil - } - } else { - if x.What == nil { - x.What = new(Ident) - } - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *InfoStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt10 := z.Extension(x.Kind); yyxt10 != nil { - z.DecExtension(&x.Kind, yyxt10) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.What != nil { // remove the if-true - x.What = nil - } - } else { - if x.What == nil { - x.What = new(Ident) - } - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.DecExtension(x.What, yyxt12) - } else { - x.What.CodecDecodeSelf(d) - } - } - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *InfoStatement) IsCodecEmpty() bool { - return !(x.Kind != 0 || false) -} - -func (RunStatement) codecSelferViaCodecgen() {} -func (x *RunStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.RW)) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.Expr); yyxt6 != nil { - z.EncExtension(x.Expr, yyxt6) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RW\"") - } else { - r.EncodeString(`RW`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.RW)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt8 := z.Extension(x.Expr); yyxt8 != nil { - z.EncExtension(x.Expr, yyxt8) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteMapEnd() - } - } -} - -func (x *RunStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RunStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RunStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "RW": - x.RW = (bool)(r.DecodeBool()) - case "Expr": - if yyxt6 := z.Extension(x.Expr); yyxt6 != nil { - z.DecExtension(&x.Expr, yyxt6) - } else { - z.DecFallback(&x.Expr, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RunStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.RW = (bool)(r.DecodeBool()) - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt10 := z.Extension(x.Expr); yyxt10 != nil { - z.DecExtension(&x.Expr, yyxt10) - } else { - z.DecFallback(&x.Expr, true) - } - for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj7-1, "") - } -} - -func (x *RunStatement) IsCodecEmpty() bool { - return !(bool(x.RW) || x.Expr != nil || false) -} - -func (LetStatement) codecSelferViaCodecgen() {} -func (x *LetStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.RW)) - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - z.EncFallback(x.What) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RW\"") - } else { - r.EncodeString(`RW`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.RW)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt10 := z.Extension(x.Name); yyxt10 != nil { - z.EncExtension(x.Name, yyxt10) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.What); yyxt11 != nil { - z.EncExtension(x.What, yyxt11) - } else { - z.EncFallback(x.What) - } - z.EncWriteMapEnd() - } - } -} - -func (x *LetStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = LetStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *LetStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "RW": - x.RW = (bool)(r.DecodeBool()) - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt6 := z.Extension(x.Name); yyxt6 != nil { - z.DecExtension(x.Name, yyxt6) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.DecExtension(&x.What, yyxt8) - } else { - z.DecFallback(&x.What, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *LetStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj9 int - var yyb9 bool - var yyhl9 bool = l >= 0 - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.RW = (bool)(r.DecodeBool()) - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt12 := z.Extension(x.Name); yyxt12 != nil { - z.DecExtension(x.Name, yyxt12) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.What); yyxt14 != nil { - z.DecExtension(&x.What, yyxt14) - } else { - z.DecFallback(&x.What, true) - } - for { - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj9-1, "") - } -} - -func (x *LetStatement) IsCodecEmpty() bool { - return !(bool(x.RW) || x.What != nil || false) -} - -func (LiveStatement) codecSelferViaCodecgen() {} -func (x *LiveStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(9) - z.EncWriteArrayElem() - r.EncodeString(string(x.ID)) - z.EncWriteArrayElem() - r.EncodeString(string(x.FB)) - z.EncWriteArrayElem() - r.EncodeString(string(x.NS)) - z.EncWriteArrayElem() - r.EncodeString(string(x.DB)) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Diff)) - z.EncWriteArrayElem() - if yyxt17 := z.Extension(x.Expr); yyxt17 != nil { - z.EncExtension(x.Expr, yyxt17) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt18 := z.Extension(x.What); yyxt18 != nil { - z.EncExtension(x.What, yyxt18) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt19 := z.Extension(x.Cond); yyxt19 != nil { - z.EncExtension(x.Cond, yyxt19) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteArrayElem() - if yyxt20 := z.Extension(x.Fetch); yyxt20 != nil { - z.EncExtension(x.Fetch, yyxt20) - } else { - x.Fetch.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(9) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"ID\"") - } else { - r.EncodeString(`ID`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.ID)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"FB\"") - } else { - r.EncodeString(`FB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.FB)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"NS\"") - } else { - r.EncodeString(`NS`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.NS)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"DB\"") - } else { - r.EncodeString(`DB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.DB)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Diff\"") - } else { - r.EncodeString(`Diff`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Diff)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt26 := z.Extension(x.Expr); yyxt26 != nil { - z.EncExtension(x.Expr, yyxt26) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt27 := z.Extension(x.What); yyxt27 != nil { - z.EncExtension(x.What, yyxt27) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt28 := z.Extension(x.Cond); yyxt28 != nil { - z.EncExtension(x.Cond, yyxt28) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Fetch\"") - } else { - r.EncodeString(`Fetch`) - } - z.EncWriteMapElemValue() - if yyxt29 := z.Extension(x.Fetch); yyxt29 != nil { - z.EncExtension(x.Fetch, yyxt29) - } else { - x.Fetch.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *LiveStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = LiveStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *LiveStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "ID": - x.ID = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "FB": - x.FB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "NS": - x.NS = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "DB": - x.DB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "Diff": - x.Diff = (bool)(r.DecodeBool()) - case "Expr": - if yyxt10 := z.Extension(x.Expr); yyxt10 != nil { - z.DecExtension(&x.Expr, yyxt10) - } else { - x.Expr.CodecDecodeSelf(d) - } - case "What": - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.DecExtension(&x.What, yyxt12) - } else { - x.What.CodecDecodeSelf(d) - } - case "Cond": - if yyxt14 := z.Extension(x.Cond); yyxt14 != nil { - z.DecExtension(&x.Cond, yyxt14) - } else { - z.DecFallback(&x.Cond, true) - } - case "Fetch": - if yyxt16 := z.Extension(x.Fetch); yyxt16 != nil { - z.DecExtension(&x.Fetch, yyxt16) - } else { - x.Fetch.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *LiveStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj17 int - var yyb17 bool - var yyhl17 bool = l >= 0 - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.ID = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.FB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.NS = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.DB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Diff = (bool)(r.DecodeBool()) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt24 := z.Extension(x.Expr); yyxt24 != nil { - z.DecExtension(&x.Expr, yyxt24) - } else { - x.Expr.CodecDecodeSelf(d) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt26 := z.Extension(x.What); yyxt26 != nil { - z.DecExtension(&x.What, yyxt26) - } else { - x.What.CodecDecodeSelf(d) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt28 := z.Extension(x.Cond); yyxt28 != nil { - z.DecExtension(&x.Cond, yyxt28) - } else { - z.DecFallback(&x.Cond, true) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt30 := z.Extension(x.Fetch); yyxt30 != nil { - z.DecExtension(&x.Fetch, yyxt30) - } else { - x.Fetch.CodecDecodeSelf(d) - } - for { - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj17-1, "") - } -} - -func (x *LiveStatement) IsCodecEmpty() bool { - return !(x.ID != "" || x.FB != "" || x.NS != "" || x.DB != "" || bool(x.Diff) || len(x.Expr) != 0 || len(x.What) != 0 || x.Cond != nil || len(x.Fetch) != 0 || false) -} - -func (KillStatement) codecSelferViaCodecgen() {} -func (x *KillStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeString(string(x.FB)) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"FB\"") - } else { - r.EncodeString(`FB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.FB)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *KillStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = KillStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *KillStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "FB": - x.FB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "What": - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.DecExtension(&x.What, yyxt6) - } else { - x.What.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *KillStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.FB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt10 := z.Extension(x.What); yyxt10 != nil { - z.DecExtension(&x.What, yyxt10) - } else { - x.What.CodecDecodeSelf(d) - } - for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj7-1, "") - } -} - -func (x *KillStatement) IsCodecEmpty() bool { - return !(x.FB != "" || len(x.What) != 0 || false) -} - -func (ReturnStatement) codecSelferViaCodecgen() {} -func (x *ReturnStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.RW)) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RW\"") - } else { - r.EncodeString(`RW`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.RW)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *ReturnStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = ReturnStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *ReturnStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "RW": - x.RW = (bool)(r.DecodeBool()) - case "What": - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.DecExtension(&x.What, yyxt6) - } else { - x.What.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *ReturnStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.RW = (bool)(r.DecodeBool()) - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt10 := z.Extension(x.What); yyxt10 != nil { - z.DecExtension(&x.What, yyxt10) - } else { - x.What.CodecDecodeSelf(d) - } - for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj7-1, "") - } -} - -func (x *ReturnStatement) IsCodecEmpty() bool { - return !(bool(x.RW) || len(x.What) != 0 || false) -} - -func (IfelseStatement) codecSelferViaCodecgen() {} -func (x *IfelseStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.RW)) - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Cond); yyxt8 != nil { - z.EncExtension(x.Cond, yyxt8) - } else { - x.Cond.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Then); yyxt9 != nil { - z.EncExtension(x.Then, yyxt9) - } else { - x.Then.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Else); yyxt10 != nil { - z.EncExtension(x.Else, yyxt10) - } else { - z.EncFallback(x.Else) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RW\"") - } else { - r.EncodeString(`RW`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.RW)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt12 := z.Extension(x.Cond); yyxt12 != nil { - z.EncExtension(x.Cond, yyxt12) - } else { - x.Cond.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Then\"") - } else { - r.EncodeString(`Then`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Then); yyxt13 != nil { - z.EncExtension(x.Then, yyxt13) - } else { - x.Then.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Else\"") - } else { - r.EncodeString(`Else`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Else); yyxt14 != nil { - z.EncExtension(x.Else, yyxt14) - } else { - z.EncFallback(x.Else) - } - z.EncWriteMapEnd() - } - } -} - -func (x *IfelseStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = IfelseStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *IfelseStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "RW": - x.RW = (bool)(r.DecodeBool()) - case "Cond": - if yyxt6 := z.Extension(x.Cond); yyxt6 != nil { - z.DecExtension(&x.Cond, yyxt6) - } else { - x.Cond.CodecDecodeSelf(d) - } - case "Then": - if yyxt8 := z.Extension(x.Then); yyxt8 != nil { - z.DecExtension(&x.Then, yyxt8) - } else { - x.Then.CodecDecodeSelf(d) - } - case "Else": - if yyxt10 := z.Extension(x.Else); yyxt10 != nil { - z.DecExtension(&x.Else, yyxt10) - } else { - z.DecFallback(&x.Else, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *IfelseStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj11 int - var yyb11 bool - var yyhl11 bool = l >= 0 - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.RW = (bool)(r.DecodeBool()) - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Cond); yyxt14 != nil { - z.DecExtension(&x.Cond, yyxt14) - } else { - x.Cond.CodecDecodeSelf(d) - } - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.Then); yyxt16 != nil { - z.DecExtension(&x.Then, yyxt16) - } else { - x.Then.CodecDecodeSelf(d) - } - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Else); yyxt18 != nil { - z.DecExtension(&x.Else, yyxt18) - } else { - z.DecFallback(&x.Else, true) - } - for { - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj11-1, "") - } -} - -func (x *IfelseStatement) IsCodecEmpty() bool { - return !(bool(x.RW) || len(x.Cond) != 0 || len(x.Then) != 0 || x.Else != nil || false) -} - -func (SelectStatement) codecSelferViaCodecgen() {} -func (x *SelectStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(12) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.RW)) - z.EncWriteArrayElem() - if yyxt16 := z.Extension(x.Expr); yyxt16 != nil { - z.EncExtension(x.Expr, yyxt16) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt17 := z.Extension(x.What); yyxt17 != nil { - z.EncExtension(x.What, yyxt17) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt18 := z.Extension(x.Cond); yyxt18 != nil { - z.EncExtension(x.Cond, yyxt18) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteArrayElem() - if yyxt19 := z.Extension(x.Split); yyxt19 != nil { - z.EncExtension(x.Split, yyxt19) - } else { - x.Split.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt20 := z.Extension(x.Group); yyxt20 != nil { - z.EncExtension(x.Group, yyxt20) - } else { - x.Group.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt21 := z.Extension(x.Order); yyxt21 != nil { - z.EncExtension(x.Order, yyxt21) - } else { - x.Order.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt22 := z.Extension(x.Limit); yyxt22 != nil { - z.EncExtension(x.Limit, yyxt22) - } else { - z.EncFallback(x.Limit) - } - z.EncWriteArrayElem() - if yyxt23 := z.Extension(x.Start); yyxt23 != nil { - z.EncExtension(x.Start, yyxt23) - } else { - z.EncFallback(x.Start) - } - z.EncWriteArrayElem() - if yyxt24 := z.Extension(x.Fetch); yyxt24 != nil { - z.EncExtension(x.Fetch, yyxt24) - } else { - x.Fetch.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt25 := z.Extension(x.Version); yyxt25 != nil { - z.EncExtension(x.Version, yyxt25) - } else { - z.EncFallback(x.Version) - } - z.EncWriteArrayElem() - if yyxt26 := z.Extension(x.Timeout); yyxt26 != nil { - z.EncExtension(x.Timeout, yyxt26) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(12) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RW\"") - } else { - r.EncodeString(`RW`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.RW)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt28 := z.Extension(x.Expr); yyxt28 != nil { - z.EncExtension(x.Expr, yyxt28) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt29 := z.Extension(x.What); yyxt29 != nil { - z.EncExtension(x.What, yyxt29) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt30 := z.Extension(x.Cond); yyxt30 != nil { - z.EncExtension(x.Cond, yyxt30) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Split\"") - } else { - r.EncodeString(`Split`) - } - z.EncWriteMapElemValue() - if yyxt31 := z.Extension(x.Split); yyxt31 != nil { - z.EncExtension(x.Split, yyxt31) - } else { - x.Split.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Group\"") - } else { - r.EncodeString(`Group`) - } - z.EncWriteMapElemValue() - if yyxt32 := z.Extension(x.Group); yyxt32 != nil { - z.EncExtension(x.Group, yyxt32) - } else { - x.Group.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Order\"") - } else { - r.EncodeString(`Order`) - } - z.EncWriteMapElemValue() - if yyxt33 := z.Extension(x.Order); yyxt33 != nil { - z.EncExtension(x.Order, yyxt33) - } else { - x.Order.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Limit\"") - } else { - r.EncodeString(`Limit`) - } - z.EncWriteMapElemValue() - if yyxt34 := z.Extension(x.Limit); yyxt34 != nil { - z.EncExtension(x.Limit, yyxt34) - } else { - z.EncFallback(x.Limit) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Start\"") - } else { - r.EncodeString(`Start`) - } - z.EncWriteMapElemValue() - if yyxt35 := z.Extension(x.Start); yyxt35 != nil { - z.EncExtension(x.Start, yyxt35) - } else { - z.EncFallback(x.Start) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Fetch\"") - } else { - r.EncodeString(`Fetch`) - } - z.EncWriteMapElemValue() - if yyxt36 := z.Extension(x.Fetch); yyxt36 != nil { - z.EncExtension(x.Fetch, yyxt36) - } else { - x.Fetch.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Version\"") - } else { - r.EncodeString(`Version`) - } - z.EncWriteMapElemValue() - if yyxt37 := z.Extension(x.Version); yyxt37 != nil { - z.EncExtension(x.Version, yyxt37) - } else { - z.EncFallback(x.Version) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt38 := z.Extension(x.Timeout); yyxt38 != nil { - z.EncExtension(x.Timeout, yyxt38) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *SelectStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = SelectStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *SelectStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "RW": - x.RW = (bool)(r.DecodeBool()) - case "Expr": - if yyxt6 := z.Extension(x.Expr); yyxt6 != nil { - z.DecExtension(&x.Expr, yyxt6) - } else { - x.Expr.CodecDecodeSelf(d) - } - case "What": - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.DecExtension(&x.What, yyxt8) - } else { - x.What.CodecDecodeSelf(d) - } - case "Cond": - if yyxt10 := z.Extension(x.Cond); yyxt10 != nil { - z.DecExtension(&x.Cond, yyxt10) - } else { - z.DecFallback(&x.Cond, true) - } - case "Split": - if yyxt12 := z.Extension(x.Split); yyxt12 != nil { - z.DecExtension(&x.Split, yyxt12) - } else { - x.Split.CodecDecodeSelf(d) - } - case "Group": - if yyxt14 := z.Extension(x.Group); yyxt14 != nil { - z.DecExtension(&x.Group, yyxt14) - } else { - x.Group.CodecDecodeSelf(d) - } - case "Order": - if yyxt16 := z.Extension(x.Order); yyxt16 != nil { - z.DecExtension(&x.Order, yyxt16) - } else { - x.Order.CodecDecodeSelf(d) - } - case "Limit": - if yyxt18 := z.Extension(x.Limit); yyxt18 != nil { - z.DecExtension(&x.Limit, yyxt18) - } else { - z.DecFallback(&x.Limit, true) - } - case "Start": - if yyxt20 := z.Extension(x.Start); yyxt20 != nil { - z.DecExtension(&x.Start, yyxt20) - } else { - z.DecFallback(&x.Start, true) - } - case "Fetch": - if yyxt22 := z.Extension(x.Fetch); yyxt22 != nil { - z.DecExtension(&x.Fetch, yyxt22) - } else { - x.Fetch.CodecDecodeSelf(d) - } - case "Version": - if yyxt24 := z.Extension(x.Version); yyxt24 != nil { - z.DecExtension(&x.Version, yyxt24) - } else { - z.DecFallback(&x.Version, true) - } - case "Timeout": - if yyxt26 := z.Extension(x.Timeout); yyxt26 != nil { - z.DecExtension(&x.Timeout, yyxt26) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *SelectStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj27 int - var yyb27 bool - var yyhl27 bool = l >= 0 - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.RW = (bool)(r.DecodeBool()) - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt30 := z.Extension(x.Expr); yyxt30 != nil { - z.DecExtension(&x.Expr, yyxt30) - } else { - x.Expr.CodecDecodeSelf(d) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt32 := z.Extension(x.What); yyxt32 != nil { - z.DecExtension(&x.What, yyxt32) - } else { - x.What.CodecDecodeSelf(d) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt34 := z.Extension(x.Cond); yyxt34 != nil { - z.DecExtension(&x.Cond, yyxt34) - } else { - z.DecFallback(&x.Cond, true) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt36 := z.Extension(x.Split); yyxt36 != nil { - z.DecExtension(&x.Split, yyxt36) - } else { - x.Split.CodecDecodeSelf(d) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt38 := z.Extension(x.Group); yyxt38 != nil { - z.DecExtension(&x.Group, yyxt38) - } else { - x.Group.CodecDecodeSelf(d) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt40 := z.Extension(x.Order); yyxt40 != nil { - z.DecExtension(&x.Order, yyxt40) - } else { - x.Order.CodecDecodeSelf(d) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt42 := z.Extension(x.Limit); yyxt42 != nil { - z.DecExtension(&x.Limit, yyxt42) - } else { - z.DecFallback(&x.Limit, true) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt44 := z.Extension(x.Start); yyxt44 != nil { - z.DecExtension(&x.Start, yyxt44) - } else { - z.DecFallback(&x.Start, true) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt46 := z.Extension(x.Fetch); yyxt46 != nil { - z.DecExtension(&x.Fetch, yyxt46) - } else { - x.Fetch.CodecDecodeSelf(d) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt48 := z.Extension(x.Version); yyxt48 != nil { - z.DecExtension(&x.Version, yyxt48) - } else { - z.DecFallback(&x.Version, true) - } - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt50 := z.Extension(x.Timeout); yyxt50 != nil { - z.DecExtension(&x.Timeout, yyxt50) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj27++ - if yyhl27 { - yyb27 = yyj27 > l - } else { - yyb27 = z.DecCheckBreak() - } - if yyb27 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj27-1, "") - } -} - -func (x *SelectStatement) IsCodecEmpty() bool { - return !(bool(x.RW) || len(x.Expr) != 0 || len(x.What) != 0 || x.Cond != nil || len(x.Split) != 0 || len(x.Group) != 0 || len(x.Order) != 0 || x.Limit != nil || x.Start != nil || len(x.Fetch) != 0 || x.Version != nil || x.Timeout != 0 || false) -} - -func (CreateStatement) codecSelferViaCodecgen() {} -func (x *CreateStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.EncExtension(x.What, yyxt7) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Data); yyxt8 != nil { - z.EncExtension(x.Data, yyxt8) - } else { - z.EncFallback(x.Data) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.EncExtension(x.Echo, yyxt9) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Timeout); yyxt10 != nil { - z.EncExtension(x.Timeout, yyxt10) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.What); yyxt11 != nil { - z.EncExtension(x.What, yyxt11) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt12 := z.Extension(x.Data); yyxt12 != nil { - z.EncExtension(x.Data, yyxt12) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Echo\"") - } else { - r.EncodeString(`Echo`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Echo); yyxt13 != nil { - z.EncExtension(x.Echo, yyxt13) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Timeout); yyxt14 != nil { - z.EncExtension(x.Timeout, yyxt14) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *CreateStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = CreateStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *CreateStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "What": - if yyxt5 := z.Extension(x.What); yyxt5 != nil { - z.DecExtension(&x.What, yyxt5) - } else { - x.What.CodecDecodeSelf(d) - } - case "Data": - if yyxt7 := z.Extension(x.Data); yyxt7 != nil { - z.DecExtension(&x.Data, yyxt7) - } else { - z.DecFallback(&x.Data, true) - } - case "Echo": - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.DecExtension(&x.Echo, yyxt9) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Timeout": - if yyxt11 := z.Extension(x.Timeout); yyxt11 != nil { - z.DecExtension(&x.Timeout, yyxt11) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *CreateStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.What); yyxt14 != nil { - z.DecExtension(&x.What, yyxt14) - } else { - x.What.CodecDecodeSelf(d) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.Data); yyxt16 != nil { - z.DecExtension(&x.Data, yyxt16) - } else { - z.DecFallback(&x.Data, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Echo); yyxt18 != nil { - z.DecExtension(&x.Echo, yyxt18) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Timeout); yyxt20 != nil { - z.DecExtension(&x.Timeout, yyxt20) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj12-1, "") - } -} - -func (x *CreateStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || x.Data != nil || x.Echo != 0 || x.Timeout != 0 || false) -} - -func (UpdateStatement) codecSelferViaCodecgen() {} -func (x *UpdateStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(5) - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Data); yyxt9 != nil { - z.EncExtension(x.Data, yyxt9) - } else { - z.EncFallback(x.Data) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Cond); yyxt10 != nil { - z.EncExtension(x.Cond, yyxt10) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteArrayElem() - if yyxt11 := z.Extension(x.Echo); yyxt11 != nil { - z.EncExtension(x.Echo, yyxt11) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteArrayElem() - if yyxt12 := z.Extension(x.Timeout); yyxt12 != nil { - z.EncExtension(x.Timeout, yyxt12) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(5) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.What); yyxt13 != nil { - z.EncExtension(x.What, yyxt13) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Data); yyxt14 != nil { - z.EncExtension(x.Data, yyxt14) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt15 := z.Extension(x.Cond); yyxt15 != nil { - z.EncExtension(x.Cond, yyxt15) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Echo\"") - } else { - r.EncodeString(`Echo`) - } - z.EncWriteMapElemValue() - if yyxt16 := z.Extension(x.Echo); yyxt16 != nil { - z.EncExtension(x.Echo, yyxt16) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt17 := z.Extension(x.Timeout); yyxt17 != nil { - z.EncExtension(x.Timeout, yyxt17) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *UpdateStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = UpdateStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *UpdateStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "What": - if yyxt5 := z.Extension(x.What); yyxt5 != nil { - z.DecExtension(&x.What, yyxt5) - } else { - x.What.CodecDecodeSelf(d) - } - case "Data": - if yyxt7 := z.Extension(x.Data); yyxt7 != nil { - z.DecExtension(&x.Data, yyxt7) - } else { - z.DecFallback(&x.Data, true) - } - case "Cond": - if yyxt9 := z.Extension(x.Cond); yyxt9 != nil { - z.DecExtension(&x.Cond, yyxt9) - } else { - z.DecFallback(&x.Cond, true) - } - case "Echo": - if yyxt11 := z.Extension(x.Echo); yyxt11 != nil { - z.DecExtension(&x.Echo, yyxt11) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Timeout": - if yyxt13 := z.Extension(x.Timeout); yyxt13 != nil { - z.DecExtension(&x.Timeout, yyxt13) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *UpdateStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj14 int - var yyb14 bool - var yyhl14 bool = l >= 0 - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.What); yyxt16 != nil { - z.DecExtension(&x.What, yyxt16) - } else { - x.What.CodecDecodeSelf(d) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Data); yyxt18 != nil { - z.DecExtension(&x.Data, yyxt18) - } else { - z.DecFallback(&x.Data, true) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Cond); yyxt20 != nil { - z.DecExtension(&x.Cond, yyxt20) - } else { - z.DecFallback(&x.Cond, true) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt22 := z.Extension(x.Echo); yyxt22 != nil { - z.DecExtension(&x.Echo, yyxt22) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt24 := z.Extension(x.Timeout); yyxt24 != nil { - z.DecExtension(&x.Timeout, yyxt24) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj14-1, "") - } -} - -func (x *UpdateStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || x.Data != nil || x.Cond != nil || x.Echo != 0 || x.Timeout != 0 || false) -} - -func (DeleteStatement) codecSelferViaCodecgen() {} -func (x *DeleteStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.EncExtension(x.What, yyxt7) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Cond); yyxt8 != nil { - z.EncExtension(x.Cond, yyxt8) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.EncExtension(x.Echo, yyxt9) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Timeout); yyxt10 != nil { - z.EncExtension(x.Timeout, yyxt10) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.What); yyxt11 != nil { - z.EncExtension(x.What, yyxt11) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt12 := z.Extension(x.Cond); yyxt12 != nil { - z.EncExtension(x.Cond, yyxt12) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Echo\"") - } else { - r.EncodeString(`Echo`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Echo); yyxt13 != nil { - z.EncExtension(x.Echo, yyxt13) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Timeout); yyxt14 != nil { - z.EncExtension(x.Timeout, yyxt14) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *DeleteStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DeleteStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DeleteStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "What": - if yyxt5 := z.Extension(x.What); yyxt5 != nil { - z.DecExtension(&x.What, yyxt5) - } else { - x.What.CodecDecodeSelf(d) - } - case "Cond": - if yyxt7 := z.Extension(x.Cond); yyxt7 != nil { - z.DecExtension(&x.Cond, yyxt7) - } else { - z.DecFallback(&x.Cond, true) - } - case "Echo": - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.DecExtension(&x.Echo, yyxt9) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Timeout": - if yyxt11 := z.Extension(x.Timeout); yyxt11 != nil { - z.DecExtension(&x.Timeout, yyxt11) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DeleteStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.What); yyxt14 != nil { - z.DecExtension(&x.What, yyxt14) - } else { - x.What.CodecDecodeSelf(d) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.Cond); yyxt16 != nil { - z.DecExtension(&x.Cond, yyxt16) - } else { - z.DecFallback(&x.Cond, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Echo); yyxt18 != nil { - z.DecExtension(&x.Echo, yyxt18) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Timeout); yyxt20 != nil { - z.DecExtension(&x.Timeout, yyxt20) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj12-1, "") - } -} - -func (x *DeleteStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || x.Cond != nil || x.Echo != 0 || x.Timeout != 0 || false) -} - -func (RelateStatement) codecSelferViaCodecgen() {} -func (x *RelateStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(7) - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Type); yyxt10 != nil { - z.EncExtension(x.Type, yyxt10) - } else { - z.EncFallback(x.Type) - } - z.EncWriteArrayElem() - if yyxt11 := z.Extension(x.From); yyxt11 != nil { - z.EncExtension(x.From, yyxt11) - } else { - x.From.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt12 := z.Extension(x.With); yyxt12 != nil { - z.EncExtension(x.With, yyxt12) - } else { - x.With.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt13 := z.Extension(x.Data); yyxt13 != nil { - z.EncExtension(x.Data, yyxt13) - } else { - z.EncFallback(x.Data) - } - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Uniq)) - z.EncWriteArrayElem() - if yyxt15 := z.Extension(x.Echo); yyxt15 != nil { - z.EncExtension(x.Echo, yyxt15) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteArrayElem() - if yyxt16 := z.Extension(x.Timeout); yyxt16 != nil { - z.EncExtension(x.Timeout, yyxt16) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(7) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Type\"") - } else { - r.EncodeString(`Type`) - } - z.EncWriteMapElemValue() - if yyxt17 := z.Extension(x.Type); yyxt17 != nil { - z.EncExtension(x.Type, yyxt17) - } else { - z.EncFallback(x.Type) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"From\"") - } else { - r.EncodeString(`From`) - } - z.EncWriteMapElemValue() - if yyxt18 := z.Extension(x.From); yyxt18 != nil { - z.EncExtension(x.From, yyxt18) - } else { - x.From.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"With\"") - } else { - r.EncodeString(`With`) - } - z.EncWriteMapElemValue() - if yyxt19 := z.Extension(x.With); yyxt19 != nil { - z.EncExtension(x.With, yyxt19) - } else { - x.With.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt20 := z.Extension(x.Data); yyxt20 != nil { - z.EncExtension(x.Data, yyxt20) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Uniq\"") - } else { - r.EncodeString(`Uniq`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Uniq)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Echo\"") - } else { - r.EncodeString(`Echo`) - } - z.EncWriteMapElemValue() - if yyxt22 := z.Extension(x.Echo); yyxt22 != nil { - z.EncExtension(x.Echo, yyxt22) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt23 := z.Extension(x.Timeout); yyxt23 != nil { - z.EncExtension(x.Timeout, yyxt23) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *RelateStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RelateStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RelateStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Type": - if yyxt5 := z.Extension(x.Type); yyxt5 != nil { - z.DecExtension(&x.Type, yyxt5) - } else { - z.DecFallback(&x.Type, true) - } - case "From": - if yyxt7 := z.Extension(x.From); yyxt7 != nil { - z.DecExtension(&x.From, yyxt7) - } else { - x.From.CodecDecodeSelf(d) - } - case "With": - if yyxt9 := z.Extension(x.With); yyxt9 != nil { - z.DecExtension(&x.With, yyxt9) - } else { - x.With.CodecDecodeSelf(d) - } - case "Data": - if yyxt11 := z.Extension(x.Data); yyxt11 != nil { - z.DecExtension(&x.Data, yyxt11) - } else { - z.DecFallback(&x.Data, true) - } - case "Uniq": - x.Uniq = (bool)(r.DecodeBool()) - case "Echo": - if yyxt14 := z.Extension(x.Echo); yyxt14 != nil { - z.DecExtension(&x.Echo, yyxt14) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Timeout": - if yyxt16 := z.Extension(x.Timeout); yyxt16 != nil { - z.DecExtension(&x.Timeout, yyxt16) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RelateStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj17 int - var yyb17 bool - var yyhl17 bool = l >= 0 - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt19 := z.Extension(x.Type); yyxt19 != nil { - z.DecExtension(&x.Type, yyxt19) - } else { - z.DecFallback(&x.Type, true) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt21 := z.Extension(x.From); yyxt21 != nil { - z.DecExtension(&x.From, yyxt21) - } else { - x.From.CodecDecodeSelf(d) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt23 := z.Extension(x.With); yyxt23 != nil { - z.DecExtension(&x.With, yyxt23) - } else { - x.With.CodecDecodeSelf(d) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt25 := z.Extension(x.Data); yyxt25 != nil { - z.DecExtension(&x.Data, yyxt25) - } else { - z.DecFallback(&x.Data, true) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Uniq = (bool)(r.DecodeBool()) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt28 := z.Extension(x.Echo); yyxt28 != nil { - z.DecExtension(&x.Echo, yyxt28) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt30 := z.Extension(x.Timeout); yyxt30 != nil { - z.DecExtension(&x.Timeout, yyxt30) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj17-1, "") - } -} - -func (x *RelateStatement) IsCodecEmpty() bool { - return !(x.Type != nil || len(x.From) != 0 || len(x.With) != 0 || x.Data != nil || bool(x.Uniq) || x.Echo != 0 || x.Timeout != 0 || false) -} - -func (InsertStatement) codecSelferViaCodecgen() {} -func (x *InsertStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.Into == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Data); yyxt7 != nil { - z.EncExtension(x.Data, yyxt7) - } else { - z.EncFallback(x.Data) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Into); yyxt8 != nil { - z.EncExtension(x.Into, yyxt8) - } else { - x.Into.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.EncExtension(x.Echo, yyxt9) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Timeout); yyxt10 != nil { - z.EncExtension(x.Timeout, yyxt10) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.Data); yyxt11 != nil { - z.EncExtension(x.Data, yyxt11) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Into\"") - } else { - r.EncodeString(`Into`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt12 := z.Extension(x.Into); yyxt12 != nil { - z.EncExtension(x.Into, yyxt12) - } else { - x.Into.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Echo\"") - } else { - r.EncodeString(`Echo`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Echo); yyxt13 != nil { - z.EncExtension(x.Echo, yyxt13) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Timeout); yyxt14 != nil { - z.EncExtension(x.Timeout, yyxt14) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *InsertStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = InsertStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *InsertStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Data": - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.DecExtension(&x.Data, yyxt5) - } else { - z.DecFallback(&x.Data, true) - } - case "Into": - if r.TryNil() { - if x.Into != nil { // remove the if-true - x.Into = nil - } - } else { - if x.Into == nil { - x.Into = new(Table) - } - if yyxt7 := z.Extension(x.Into); yyxt7 != nil { - z.DecExtension(x.Into, yyxt7) - } else { - x.Into.CodecDecodeSelf(d) - } - } - case "Echo": - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.DecExtension(&x.Echo, yyxt9) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Timeout": - if yyxt11 := z.Extension(x.Timeout); yyxt11 != nil { - z.DecExtension(&x.Timeout, yyxt11) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *InsertStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Data); yyxt14 != nil { - z.DecExtension(&x.Data, yyxt14) - } else { - z.DecFallback(&x.Data, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Into != nil { // remove the if-true - x.Into = nil - } - } else { - if x.Into == nil { - x.Into = new(Table) - } - if yyxt16 := z.Extension(x.Into); yyxt16 != nil { - z.DecExtension(x.Into, yyxt16) - } else { - x.Into.CodecDecodeSelf(d) - } - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Echo); yyxt18 != nil { - z.DecExtension(&x.Echo, yyxt18) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Timeout); yyxt20 != nil { - z.DecExtension(&x.Timeout, yyxt20) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj12-1, "") - } -} - -func (x *InsertStatement) IsCodecEmpty() bool { - return !(x.Data != nil || x.Echo != 0 || x.Timeout != 0 || false) -} - -func (UpsertStatement) codecSelferViaCodecgen() {} -func (x *UpsertStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.Into == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Data); yyxt7 != nil { - z.EncExtension(x.Data, yyxt7) - } else { - z.EncFallback(x.Data) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Into); yyxt8 != nil { - z.EncExtension(x.Into, yyxt8) - } else { - x.Into.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.EncExtension(x.Echo, yyxt9) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Timeout); yyxt10 != nil { - z.EncExtension(x.Timeout, yyxt10) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.Data); yyxt11 != nil { - z.EncExtension(x.Data, yyxt11) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Into\"") - } else { - r.EncodeString(`Into`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt12 := z.Extension(x.Into); yyxt12 != nil { - z.EncExtension(x.Into, yyxt12) - } else { - x.Into.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Echo\"") - } else { - r.EncodeString(`Echo`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Echo); yyxt13 != nil { - z.EncExtension(x.Echo, yyxt13) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Echo) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Echo) - } else { - r.EncodeInt(int64(x.Echo)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Timeout\"") - } else { - r.EncodeString(`Timeout`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Timeout); yyxt14 != nil { - z.EncExtension(x.Timeout, yyxt14) - } else { - r.EncodeInt(int64(x.Timeout)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *UpsertStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = UpsertStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *UpsertStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Data": - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.DecExtension(&x.Data, yyxt5) - } else { - z.DecFallback(&x.Data, true) - } - case "Into": - if r.TryNil() { - if x.Into != nil { // remove the if-true - x.Into = nil - } - } else { - if x.Into == nil { - x.Into = new(Table) - } - if yyxt7 := z.Extension(x.Into); yyxt7 != nil { - z.DecExtension(x.Into, yyxt7) - } else { - x.Into.CodecDecodeSelf(d) - } - } - case "Echo": - if yyxt9 := z.Extension(x.Echo); yyxt9 != nil { - z.DecExtension(&x.Echo, yyxt9) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Timeout": - if yyxt11 := z.Extension(x.Timeout); yyxt11 != nil { - z.DecExtension(&x.Timeout, yyxt11) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *UpsertStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Data); yyxt14 != nil { - z.DecExtension(&x.Data, yyxt14) - } else { - z.DecFallback(&x.Data, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Into != nil { // remove the if-true - x.Into = nil - } - } else { - if x.Into == nil { - x.Into = new(Table) - } - if yyxt16 := z.Extension(x.Into); yyxt16 != nil { - z.DecExtension(x.Into, yyxt16) - } else { - x.Into.CodecDecodeSelf(d) - } - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Echo); yyxt18 != nil { - z.DecExtension(&x.Echo, yyxt18) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Echo) - } else { - x.Echo = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Timeout); yyxt20 != nil { - z.DecExtension(&x.Timeout, yyxt20) - } else { - x.Timeout = (time.Duration)(r.DecodeInt64()) - } - for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj12-1, "") - } -} - -func (x *UpsertStatement) IsCodecEmpty() bool { - return !(x.Data != nil || x.Echo != 0 || x.Timeout != 0 || false) -} - -func (DefineNamespaceStatement) codecSelferViaCodecgen() {} -func (x *DefineNamespaceStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Name); yyxt4 != nil { - z.EncExtension(x.Name, yyxt4) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *DefineNamespaceStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineNamespaceStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineNamespaceStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineNamespaceStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt8 := z.Extension(x.Name); yyxt8 != nil { - z.DecExtension(x.Name, yyxt8) - } else { - x.Name.CodecDecodeSelf(d) - } - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *DefineNamespaceStatement) IsCodecEmpty() bool { - return !(false) -} - -func (RemoveNamespaceStatement) codecSelferViaCodecgen() {} -func (x *RemoveNamespaceStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Name); yyxt4 != nil { - z.EncExtension(x.Name, yyxt4) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveNamespaceStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveNamespaceStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveNamespaceStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveNamespaceStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt8 := z.Extension(x.Name); yyxt8 != nil { - z.DecExtension(x.Name, yyxt8) - } else { - x.Name.CodecDecodeSelf(d) - } - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *RemoveNamespaceStatement) IsCodecEmpty() bool { - return !(false) -} - -func (DefineDatabaseStatement) codecSelferViaCodecgen() {} -func (x *DefineDatabaseStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Name); yyxt4 != nil { - z.EncExtension(x.Name, yyxt4) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *DefineDatabaseStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineDatabaseStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineDatabaseStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineDatabaseStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt8 := z.Extension(x.Name); yyxt8 != nil { - z.DecExtension(x.Name, yyxt8) - } else { - x.Name.CodecDecodeSelf(d) - } - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *DefineDatabaseStatement) IsCodecEmpty() bool { - return !(false) -} - -func (RemoveDatabaseStatement) codecSelferViaCodecgen() {} -func (x *RemoveDatabaseStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Name); yyxt4 != nil { - z.EncExtension(x.Name, yyxt4) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveDatabaseStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveDatabaseStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveDatabaseStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveDatabaseStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt8 := z.Extension(x.Name); yyxt8 != nil { - z.DecExtension(x.Name, yyxt8) - } else { - x.Name.CodecDecodeSelf(d) - } - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *RemoveDatabaseStatement) IsCodecEmpty() bool { - return !(false) -} - -func (DefineLoginStatement) codecSelferViaCodecgen() {} -func (x *DefineLoginStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.User == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(5) - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Kind); yyxt8 != nil { - z.EncExtension(x.Kind, yyxt8) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.User); yyxt9 != nil { - z.EncExtension(x.User, yyxt9) - } else { - x.User.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if x.Pass == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Pass)) - } // end block: if x.Pass slice == nil - z.EncWriteArrayElem() - if x.Hash == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Hash)) - } // end block: if x.Hash slice == nil - z.EncWriteArrayElem() - if x.Code == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Code)) - } // end block: if x.Code slice == nil - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(5) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Kind\"") - } else { - r.EncodeString(`Kind`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Kind); yyxt13 != nil { - z.EncExtension(x.Kind, yyxt13) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"User\"") - } else { - r.EncodeString(`User`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt14 := z.Extension(x.User); yyxt14 != nil { - z.EncExtension(x.User, yyxt14) - } else { - x.User.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Pass\"") - } else { - r.EncodeString(`Pass`) - } - z.EncWriteMapElemValue() - if x.Pass == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Pass)) - } // end block: if x.Pass slice == nil - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Hash\"") - } else { - r.EncodeString(`Hash`) - } - z.EncWriteMapElemValue() - if x.Hash == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Hash)) - } // end block: if x.Hash slice == nil - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Code\"") - } else { - r.EncodeString(`Code`) - } - z.EncWriteMapElemValue() - if x.Code == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Code)) - } // end block: if x.Code slice == nil - z.EncWriteMapEnd() - } - } -} - -func (x *DefineLoginStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineLoginStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineLoginStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Kind": - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.DecExtension(&x.Kind, yyxt5) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "User": - if r.TryNil() { - if x.User != nil { // remove the if-true - x.User = nil - } - } else { - if x.User == nil { - x.User = new(Ident) - } - if yyxt7 := z.Extension(x.User); yyxt7 != nil { - z.DecExtension(x.User, yyxt7) - } else { - x.User.CodecDecodeSelf(d) - } - } - case "Pass": - x.Pass = z.DecodeBytesInto(([]byte)(x.Pass)) - case "Hash": - x.Hash = z.DecodeBytesInto(([]byte)(x.Hash)) - case "Code": - x.Code = z.DecodeBytesInto(([]byte)(x.Code)) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineLoginStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj14 int - var yyb14 bool - var yyhl14 bool = l >= 0 - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.Kind); yyxt16 != nil { - z.DecExtension(&x.Kind, yyxt16) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.User != nil { // remove the if-true - x.User = nil - } - } else { - if x.User == nil { - x.User = new(Ident) - } - if yyxt18 := z.Extension(x.User); yyxt18 != nil { - z.DecExtension(x.User, yyxt18) - } else { - x.User.CodecDecodeSelf(d) - } - } - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Pass = z.DecodeBytesInto(([]byte)(x.Pass)) - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Hash = z.DecodeBytesInto(([]byte)(x.Hash)) - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Code = z.DecodeBytesInto(([]byte)(x.Code)) - for { - yyj14++ - if yyhl14 { - yyb14 = yyj14 > l - } else { - yyb14 = z.DecCheckBreak() - } - if yyb14 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj14-1, "") - } -} - -func (x *DefineLoginStatement) IsCodecEmpty() bool { - return !(x.Kind != 0 || len(x.Pass) != 0 || len(x.Hash) != 0 || len(x.Code) != 0 || false) -} - -func (RemoveLoginStatement) codecSelferViaCodecgen() {} -func (x *RemoveLoginStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.User == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.EncExtension(x.Kind, yyxt5) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.User); yyxt6 != nil { - z.EncExtension(x.User, yyxt6) - } else { - x.User.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Kind\"") - } else { - r.EncodeString(`Kind`) - } - z.EncWriteMapElemValue() - if yyxt7 := z.Extension(x.Kind); yyxt7 != nil { - z.EncExtension(x.Kind, yyxt7) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"User\"") - } else { - r.EncodeString(`User`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt8 := z.Extension(x.User); yyxt8 != nil { - z.EncExtension(x.User, yyxt8) - } else { - x.User.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveLoginStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveLoginStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveLoginStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Kind": - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.DecExtension(&x.Kind, yyxt5) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "User": - if r.TryNil() { - if x.User != nil { // remove the if-true - x.User = nil - } - } else { - if x.User == nil { - x.User = new(Ident) - } - if yyxt7 := z.Extension(x.User); yyxt7 != nil { - z.DecExtension(x.User, yyxt7) - } else { - x.User.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveLoginStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt10 := z.Extension(x.Kind); yyxt10 != nil { - z.DecExtension(&x.Kind, yyxt10) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.User != nil { // remove the if-true - x.User = nil - } - } else { - if x.User == nil { - x.User = new(Ident) - } - if yyxt12 := z.Extension(x.User); yyxt12 != nil { - z.DecExtension(x.User, yyxt12) - } else { - x.User.CodecDecodeSelf(d) - } - } - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *RemoveLoginStatement) IsCodecEmpty() bool { - return !(x.Kind != 0 || false) -} - -func (DefineTokenStatement) codecSelferViaCodecgen() {} -func (x *DefineTokenStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.Name == nil - var yyn5 bool = x.What == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(5) - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Kind); yyxt8 != nil { - z.EncExtension(x.Kind, yyxt8) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Name); yyxt9 != nil { - z.EncExtension(x.Name, yyxt9) - } else { - x.Name.CodecEncodeSelf(e) - } - } - if yyn5 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.What); yyxt10 != nil { - z.EncExtension(x.What, yyxt10) - } else { - x.What.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - r.EncodeString(string(x.Type)) - z.EncWriteArrayElem() - if x.Code == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Code)) - } // end block: if x.Code slice == nil - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(5) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Kind\"") - } else { - r.EncodeString(`Kind`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Kind); yyxt13 != nil { - z.EncExtension(x.Kind, yyxt13) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt14 := z.Extension(x.Name); yyxt14 != nil { - z.EncExtension(x.Name, yyxt14) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyn5 { - r.EncodeNil() - } else { - if yyxt15 := z.Extension(x.What); yyxt15 != nil { - z.EncExtension(x.What, yyxt15) - } else { - x.What.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Type\"") - } else { - r.EncodeString(`Type`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Type)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Code\"") - } else { - r.EncodeString(`Code`) - } - z.EncWriteMapElemValue() - if x.Code == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Code)) - } // end block: if x.Code slice == nil - z.EncWriteMapEnd() - } - } -} - -func (x *DefineTokenStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineTokenStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineTokenStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Kind": - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.DecExtension(&x.Kind, yyxt5) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.DecExtension(x.Name, yyxt7) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if r.TryNil() { - if x.What != nil { // remove the if-true - x.What = nil - } - } else { - if x.What == nil { - x.What = new(Ident) - } - if yyxt9 := z.Extension(x.What); yyxt9 != nil { - z.DecExtension(x.What, yyxt9) - } else { - x.What.CodecDecodeSelf(d) - } - } - case "Type": - x.Type = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "Code": - x.Code = z.DecodeBytesInto(([]byte)(x.Code)) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineTokenStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj13 int - var yyb13 bool - var yyhl13 bool = l >= 0 - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l - } else { - yyb13 = z.DecCheckBreak() - } - if yyb13 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt15 := z.Extension(x.Kind); yyxt15 != nil { - z.DecExtension(&x.Kind, yyxt15) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l - } else { - yyb13 = z.DecCheckBreak() - } - if yyb13 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt17 := z.Extension(x.Name); yyxt17 != nil { - z.DecExtension(x.Name, yyxt17) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l - } else { - yyb13 = z.DecCheckBreak() - } - if yyb13 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.What != nil { // remove the if-true - x.What = nil - } - } else { - if x.What == nil { - x.What = new(Ident) - } - if yyxt19 := z.Extension(x.What); yyxt19 != nil { - z.DecExtension(x.What, yyxt19) - } else { - x.What.CodecDecodeSelf(d) - } - } - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l - } else { - yyb13 = z.DecCheckBreak() - } - if yyb13 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Type = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l - } else { - yyb13 = z.DecCheckBreak() - } - if yyb13 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Code = z.DecodeBytesInto(([]byte)(x.Code)) - for { - yyj13++ - if yyhl13 { - yyb13 = yyj13 > l - } else { - yyb13 = z.DecCheckBreak() - } - if yyb13 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj13-1, "") - } -} - -func (x *DefineTokenStatement) IsCodecEmpty() bool { - return !(x.Kind != 0 || x.Type != "" || len(x.Code) != 0 || false) -} - -func (RemoveTokenStatement) codecSelferViaCodecgen() {} -func (x *RemoveTokenStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.Name == nil - var yyn5 bool = x.What == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.Kind); yyxt6 != nil { - z.EncExtension(x.Kind, yyxt6) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - if yyn5 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Kind\"") - } else { - r.EncodeString(`Kind`) - } - z.EncWriteMapElemValue() - if yyxt9 := z.Extension(x.Kind); yyxt9 != nil { - z.EncExtension(x.Kind, yyxt9) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Kind) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Kind) - } else { - r.EncodeInt(int64(x.Kind)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt10 := z.Extension(x.Name); yyxt10 != nil { - z.EncExtension(x.Name, yyxt10) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyn5 { - r.EncodeNil() - } else { - if yyxt11 := z.Extension(x.What); yyxt11 != nil { - z.EncExtension(x.What, yyxt11) - } else { - x.What.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveTokenStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveTokenStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveTokenStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Kind": - if yyxt5 := z.Extension(x.Kind); yyxt5 != nil { - z.DecExtension(&x.Kind, yyxt5) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.DecExtension(x.Name, yyxt7) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if r.TryNil() { - if x.What != nil { // remove the if-true - x.What = nil - } - } else { - if x.What == nil { - x.What = new(Ident) - } - if yyxt9 := z.Extension(x.What); yyxt9 != nil { - z.DecExtension(x.What, yyxt9) - } else { - x.What.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveTokenStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj10 int - var yyb10 bool - var yyhl10 bool = l >= 0 - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.Kind); yyxt12 != nil { - z.DecExtension(&x.Kind, yyxt12) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Kind) - } else { - x.Kind = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt14 := z.Extension(x.Name); yyxt14 != nil { - z.DecExtension(x.Name, yyxt14) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.What != nil { // remove the if-true - x.What = nil - } - } else { - if x.What == nil { - x.What = new(Ident) - } - if yyxt16 := z.Extension(x.What); yyxt16 != nil { - z.DecExtension(x.What, yyxt16) - } else { - x.What.CodecDecodeSelf(d) - } - } - for { - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj10-1, "") - } -} - -func (x *RemoveTokenStatement) IsCodecEmpty() bool { - return !(x.Kind != 0 || false) -} - -func (DefineScopeStatement) codecSelferViaCodecgen() {} -func (x *DefineScopeStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(8) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt11 := z.Extension(x.Name); yyxt11 != nil { - z.EncExtension(x.Name, yyxt11) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt12 := z.Extension(x.Time); yyxt12 != nil { - z.EncExtension(x.Time, yyxt12) - } else { - r.EncodeInt(int64(x.Time)) - } - z.EncWriteArrayElem() - if x.Code == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Code)) - } // end block: if x.Code slice == nil - z.EncWriteArrayElem() - if yyxt14 := z.Extension(x.Signup); yyxt14 != nil { - z.EncExtension(x.Signup, yyxt14) - } else { - z.EncFallback(x.Signup) - } - z.EncWriteArrayElem() - if yyxt15 := z.Extension(x.Signin); yyxt15 != nil { - z.EncExtension(x.Signin, yyxt15) - } else { - z.EncFallback(x.Signin) - } - z.EncWriteArrayElem() - if yyxt16 := z.Extension(x.Connect); yyxt16 != nil { - z.EncExtension(x.Connect, yyxt16) - } else { - z.EncFallback(x.Connect) - } - z.EncWriteArrayElem() - if yyxt17 := z.Extension(x.OnSignup); yyxt17 != nil { - z.EncExtension(x.OnSignup, yyxt17) - } else { - z.EncFallback(x.OnSignup) - } - z.EncWriteArrayElem() - if yyxt18 := z.Extension(x.OnSignin); yyxt18 != nil { - z.EncExtension(x.OnSignin, yyxt18) - } else { - z.EncFallback(x.OnSignin) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(8) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt19 := z.Extension(x.Name); yyxt19 != nil { - z.EncExtension(x.Name, yyxt19) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Time\"") - } else { - r.EncodeString(`Time`) - } - z.EncWriteMapElemValue() - if yyxt20 := z.Extension(x.Time); yyxt20 != nil { - z.EncExtension(x.Time, yyxt20) - } else { - r.EncodeInt(int64(x.Time)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Code\"") - } else { - r.EncodeString(`Code`) - } - z.EncWriteMapElemValue() - if x.Code == nil { - r.EncodeNil() - } else { - r.EncodeStringBytesRaw([]byte(x.Code)) - } // end block: if x.Code slice == nil - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Signup\"") - } else { - r.EncodeString(`Signup`) - } - z.EncWriteMapElemValue() - if yyxt22 := z.Extension(x.Signup); yyxt22 != nil { - z.EncExtension(x.Signup, yyxt22) - } else { - z.EncFallback(x.Signup) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Signin\"") - } else { - r.EncodeString(`Signin`) - } - z.EncWriteMapElemValue() - if yyxt23 := z.Extension(x.Signin); yyxt23 != nil { - z.EncExtension(x.Signin, yyxt23) - } else { - z.EncFallback(x.Signin) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Connect\"") - } else { - r.EncodeString(`Connect`) - } - z.EncWriteMapElemValue() - if yyxt24 := z.Extension(x.Connect); yyxt24 != nil { - z.EncExtension(x.Connect, yyxt24) - } else { - z.EncFallback(x.Connect) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"OnSignup\"") - } else { - r.EncodeString(`OnSignup`) - } - z.EncWriteMapElemValue() - if yyxt25 := z.Extension(x.OnSignup); yyxt25 != nil { - z.EncExtension(x.OnSignup, yyxt25) - } else { - z.EncFallback(x.OnSignup) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"OnSignin\"") - } else { - r.EncodeString(`OnSignin`) - } - z.EncWriteMapElemValue() - if yyxt26 := z.Extension(x.OnSignin); yyxt26 != nil { - z.EncExtension(x.OnSignin, yyxt26) - } else { - z.EncFallback(x.OnSignin) - } - z.EncWriteMapEnd() - } - } -} - -func (x *DefineScopeStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineScopeStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineScopeStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "Time": - if yyxt7 := z.Extension(x.Time); yyxt7 != nil { - z.DecExtension(&x.Time, yyxt7) - } else { - x.Time = (time.Duration)(r.DecodeInt64()) - } - case "Code": - x.Code = z.DecodeBytesInto(([]byte)(x.Code)) - case "Signup": - if yyxt11 := z.Extension(x.Signup); yyxt11 != nil { - z.DecExtension(&x.Signup, yyxt11) - } else { - z.DecFallback(&x.Signup, true) - } - case "Signin": - if yyxt13 := z.Extension(x.Signin); yyxt13 != nil { - z.DecExtension(&x.Signin, yyxt13) - } else { - z.DecFallback(&x.Signin, true) - } - case "Connect": - if yyxt15 := z.Extension(x.Connect); yyxt15 != nil { - z.DecExtension(&x.Connect, yyxt15) - } else { - z.DecFallback(&x.Connect, true) - } - case "OnSignup": - if yyxt17 := z.Extension(x.OnSignup); yyxt17 != nil { - z.DecExtension(&x.OnSignup, yyxt17) - } else { - z.DecFallback(&x.OnSignup, true) - } - case "OnSignin": - if yyxt19 := z.Extension(x.OnSignin); yyxt19 != nil { - z.DecExtension(&x.OnSignin, yyxt19) - } else { - z.DecFallback(&x.OnSignin, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineScopeStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj20 int - var yyb20 bool - var yyhl20 bool = l >= 0 - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt22 := z.Extension(x.Name); yyxt22 != nil { - z.DecExtension(x.Name, yyxt22) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt24 := z.Extension(x.Time); yyxt24 != nil { - z.DecExtension(&x.Time, yyxt24) - } else { - x.Time = (time.Duration)(r.DecodeInt64()) - } - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Code = z.DecodeBytesInto(([]byte)(x.Code)) - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt28 := z.Extension(x.Signup); yyxt28 != nil { - z.DecExtension(&x.Signup, yyxt28) - } else { - z.DecFallback(&x.Signup, true) - } - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt30 := z.Extension(x.Signin); yyxt30 != nil { - z.DecExtension(&x.Signin, yyxt30) - } else { - z.DecFallback(&x.Signin, true) - } - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt32 := z.Extension(x.Connect); yyxt32 != nil { - z.DecExtension(&x.Connect, yyxt32) - } else { - z.DecFallback(&x.Connect, true) - } - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt34 := z.Extension(x.OnSignup); yyxt34 != nil { - z.DecExtension(&x.OnSignup, yyxt34) - } else { - z.DecFallback(&x.OnSignup, true) - } - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt36 := z.Extension(x.OnSignin); yyxt36 != nil { - z.DecExtension(&x.OnSignin, yyxt36) - } else { - z.DecFallback(&x.OnSignin, true) - } - for { - yyj20++ - if yyhl20 { - yyb20 = yyj20 > l - } else { - yyb20 = z.DecCheckBreak() - } - if yyb20 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj20-1, "") - } -} - -func (x *DefineScopeStatement) IsCodecEmpty() bool { - return !(x.Time != 0 || len(x.Code) != 0 || x.Signup != nil || x.Signin != nil || x.Connect != nil || x.OnSignup != nil || x.OnSignin != nil || false) -} - -func (RemoveScopeStatement) codecSelferViaCodecgen() {} -func (x *RemoveScopeStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Name); yyxt4 != nil { - z.EncExtension(x.Name, yyxt4) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveScopeStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveScopeStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveScopeStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveScopeStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt8 := z.Extension(x.Name); yyxt8 != nil { - z.DecExtension(x.Name, yyxt8) - } else { - x.Name.CodecDecodeSelf(d) - } - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *RemoveScopeStatement) IsCodecEmpty() bool { - return !(false) -} - -func (DefineTableStatement) codecSelferViaCodecgen() {} -func (x *DefineTableStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(11) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt14 := z.Extension(x.Name); yyxt14 != nil { - z.EncExtension(x.Name, yyxt14) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt15 := z.Extension(x.What); yyxt15 != nil { - z.EncExtension(x.What, yyxt15) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Full)) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Vers)) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Drop)) - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Lock)) - z.EncWriteArrayElem() - if yyxt20 := z.Extension(x.Expr); yyxt20 != nil { - z.EncExtension(x.Expr, yyxt20) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt21 := z.Extension(x.From); yyxt21 != nil { - z.EncExtension(x.From, yyxt21) - } else { - x.From.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt22 := z.Extension(x.Cond); yyxt22 != nil { - z.EncExtension(x.Cond, yyxt22) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteArrayElem() - if yyxt23 := z.Extension(x.Group); yyxt23 != nil { - z.EncExtension(x.Group, yyxt23) - } else { - x.Group.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt24 := z.Extension(x.Perms); yyxt24 != nil { - z.EncExtension(x.Perms, yyxt24) - } else { - z.EncFallback(x.Perms) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(11) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt25 := z.Extension(x.Name); yyxt25 != nil { - z.EncExtension(x.Name, yyxt25) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt26 := z.Extension(x.What); yyxt26 != nil { - z.EncExtension(x.What, yyxt26) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Full\"") - } else { - r.EncodeString(`Full`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Full)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Vers\"") - } else { - r.EncodeString(`Vers`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Vers)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Drop\"") - } else { - r.EncodeString(`Drop`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Drop)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Lock\"") - } else { - r.EncodeString(`Lock`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Lock)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt31 := z.Extension(x.Expr); yyxt31 != nil { - z.EncExtension(x.Expr, yyxt31) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"From\"") - } else { - r.EncodeString(`From`) - } - z.EncWriteMapElemValue() - if yyxt32 := z.Extension(x.From); yyxt32 != nil { - z.EncExtension(x.From, yyxt32) - } else { - x.From.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt33 := z.Extension(x.Cond); yyxt33 != nil { - z.EncExtension(x.Cond, yyxt33) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Group\"") - } else { - r.EncodeString(`Group`) - } - z.EncWriteMapElemValue() - if yyxt34 := z.Extension(x.Group); yyxt34 != nil { - z.EncExtension(x.Group, yyxt34) - } else { - x.Group.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Perms\"") - } else { - r.EncodeString(`Perms`) - } - z.EncWriteMapElemValue() - if yyxt35 := z.Extension(x.Perms); yyxt35 != nil { - z.EncExtension(x.Perms, yyxt35) - } else { - z.EncFallback(x.Perms) - } - z.EncWriteMapEnd() - } - } -} - -func (x *DefineTableStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineTableStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineTableStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - case "Full": - x.Full = (bool)(r.DecodeBool()) - case "Vers": - x.Vers = (bool)(r.DecodeBool()) - case "Drop": - x.Drop = (bool)(r.DecodeBool()) - case "Lock": - x.Lock = (bool)(r.DecodeBool()) - case "Expr": - if yyxt13 := z.Extension(x.Expr); yyxt13 != nil { - z.DecExtension(&x.Expr, yyxt13) - } else { - x.Expr.CodecDecodeSelf(d) - } - case "From": - if yyxt15 := z.Extension(x.From); yyxt15 != nil { - z.DecExtension(&x.From, yyxt15) - } else { - x.From.CodecDecodeSelf(d) - } - case "Cond": - if yyxt17 := z.Extension(x.Cond); yyxt17 != nil { - z.DecExtension(&x.Cond, yyxt17) - } else { - z.DecFallback(&x.Cond, true) - } - case "Group": - if yyxt19 := z.Extension(x.Group); yyxt19 != nil { - z.DecExtension(&x.Group, yyxt19) - } else { - x.Group.CodecDecodeSelf(d) - } - case "Perms": - if yyxt21 := z.Extension(x.Perms); yyxt21 != nil { - z.DecExtension(&x.Perms, yyxt21) - } else { - z.DecFallback(&x.Perms, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineTableStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj22 int - var yyb22 bool - var yyhl22 bool = l >= 0 - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt24 := z.Extension(x.Name); yyxt24 != nil { - z.DecExtension(x.Name, yyxt24) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt26 := z.Extension(x.What); yyxt26 != nil { - z.DecExtension(&x.What, yyxt26) - } else { - x.What.CodecDecodeSelf(d) - } - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Full = (bool)(r.DecodeBool()) - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Vers = (bool)(r.DecodeBool()) - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Drop = (bool)(r.DecodeBool()) - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Lock = (bool)(r.DecodeBool()) - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt32 := z.Extension(x.Expr); yyxt32 != nil { - z.DecExtension(&x.Expr, yyxt32) - } else { - x.Expr.CodecDecodeSelf(d) - } - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt34 := z.Extension(x.From); yyxt34 != nil { - z.DecExtension(&x.From, yyxt34) - } else { - x.From.CodecDecodeSelf(d) - } - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt36 := z.Extension(x.Cond); yyxt36 != nil { - z.DecExtension(&x.Cond, yyxt36) - } else { - z.DecFallback(&x.Cond, true) - } - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt38 := z.Extension(x.Group); yyxt38 != nil { - z.DecExtension(&x.Group, yyxt38) - } else { - x.Group.CodecDecodeSelf(d) - } - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt40 := z.Extension(x.Perms); yyxt40 != nil { - z.DecExtension(&x.Perms, yyxt40) - } else { - z.DecFallback(&x.Perms, true) - } - for { - yyj22++ - if yyhl22 { - yyb22 = yyj22 > l - } else { - yyb22 = z.DecCheckBreak() - } - if yyb22 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj22-1, "") - } -} - -func (x *DefineTableStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || bool(x.Full) || bool(x.Vers) || bool(x.Drop) || bool(x.Lock) || len(x.Expr) != 0 || len(x.From) != 0 || x.Cond != nil || len(x.Group) != 0 || x.Perms != nil || false) -} - -func (RemoveTableStatement) codecSelferViaCodecgen() {} -func (x *RemoveTableStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.What); yyxt4 != nil { - z.EncExtension(x.What, yyxt4) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.What); yyxt5 != nil { - z.EncExtension(x.What, yyxt5) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveTableStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveTableStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveTableStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "What": - if yyxt5 := z.Extension(x.What); yyxt5 != nil { - z.DecExtension(&x.What, yyxt5) - } else { - x.What.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveTableStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.DecExtension(&x.What, yyxt8) - } else { - x.What.CodecDecodeSelf(d) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *RemoveTableStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || false) -} - -func (DefineEventStatement) codecSelferViaCodecgen() {} -func (x *DefineEventStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.When); yyxt9 != nil { - z.EncExtension(x.When, yyxt9) - } else { - z.EncFallback(x.When) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Then); yyxt10 != nil { - z.EncExtension(x.Then, yyxt10) - } else { - z.EncFallback(x.Then) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt11 := z.Extension(x.Name); yyxt11 != nil { - z.EncExtension(x.Name, yyxt11) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.EncExtension(x.What, yyxt12) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"When\"") - } else { - r.EncodeString(`When`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.When); yyxt13 != nil { - z.EncExtension(x.When, yyxt13) - } else { - z.EncFallback(x.When) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Then\"") - } else { - r.EncodeString(`Then`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Then); yyxt14 != nil { - z.EncExtension(x.Then, yyxt14) - } else { - z.EncFallback(x.Then) - } - z.EncWriteMapEnd() - } - } -} - -func (x *DefineEventStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineEventStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineEventStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - case "When": - if yyxt9 := z.Extension(x.When); yyxt9 != nil { - z.DecExtension(&x.When, yyxt9) - } else { - z.DecFallback(&x.When, true) - } - case "Then": - if yyxt11 := z.Extension(x.Then); yyxt11 != nil { - z.DecExtension(&x.Then, yyxt11) - } else { - z.DecFallback(&x.Then, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineEventStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt14 := z.Extension(x.Name); yyxt14 != nil { - z.DecExtension(x.Name, yyxt14) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.What); yyxt16 != nil { - z.DecExtension(&x.What, yyxt16) - } else { - x.What.CodecDecodeSelf(d) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.When); yyxt18 != nil { - z.DecExtension(&x.When, yyxt18) - } else { - z.DecFallback(&x.When, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Then); yyxt20 != nil { - z.DecExtension(&x.Then, yyxt20) - } else { - z.DecFallback(&x.Then, true) - } - for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj12-1, "") - } -} - -func (x *DefineEventStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || x.When != nil || x.Then != nil || false) -} - -func (RemoveEventStatement) codecSelferViaCodecgen() {} -func (x *RemoveEventStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveEventStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveEventStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveEventStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveEventStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt10 := z.Extension(x.Name); yyxt10 != nil { - z.DecExtension(x.Name, yyxt10) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.DecExtension(&x.What, yyxt12) - } else { - x.What.CodecDecodeSelf(d) - } - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *RemoveEventStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || false) -} - -func (DefineFieldStatement) codecSelferViaCodecgen() {} -func (x *DefineFieldStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(8) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt11 := z.Extension(x.Name); yyxt11 != nil { - z.EncExtension(x.Name, yyxt11) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.EncExtension(x.What, yyxt12) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt13 := z.Extension(x.Perms); yyxt13 != nil { - z.EncExtension(x.Perms, yyxt13) - } else { - z.EncFallback(x.Perms) - } - z.EncWriteArrayElem() - r.EncodeString(string(x.Type)) - z.EncWriteArrayElem() - r.EncodeString(string(x.Kind)) - z.EncWriteArrayElem() - if yyxt16 := z.Extension(x.Value); yyxt16 != nil { - z.EncExtension(x.Value, yyxt16) - } else { - z.EncFallback(x.Value) - } - z.EncWriteArrayElem() - if yyxt17 := z.Extension(x.Assert); yyxt17 != nil { - z.EncExtension(x.Assert, yyxt17) - } else { - z.EncFallback(x.Assert) - } - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.Priority)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(8) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt19 := z.Extension(x.Name); yyxt19 != nil { - z.EncExtension(x.Name, yyxt19) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt20 := z.Extension(x.What); yyxt20 != nil { - z.EncExtension(x.What, yyxt20) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Perms\"") - } else { - r.EncodeString(`Perms`) - } - z.EncWriteMapElemValue() - if yyxt21 := z.Extension(x.Perms); yyxt21 != nil { - z.EncExtension(x.Perms, yyxt21) - } else { - z.EncFallback(x.Perms) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Type\"") - } else { - r.EncodeString(`Type`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Type)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Kind\"") - } else { - r.EncodeString(`Kind`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Kind)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Value\"") - } else { - r.EncodeString(`Value`) - } - z.EncWriteMapElemValue() - if yyxt24 := z.Extension(x.Value); yyxt24 != nil { - z.EncExtension(x.Value, yyxt24) - } else { - z.EncFallback(x.Value) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Assert\"") - } else { - r.EncodeString(`Assert`) - } - z.EncWriteMapElemValue() - if yyxt25 := z.Extension(x.Assert); yyxt25 != nil { - z.EncExtension(x.Assert, yyxt25) - } else { - z.EncFallback(x.Assert) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Priority\"") - } else { - r.EncodeString(`Priority`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.Priority)) - z.EncWriteMapEnd() - } - } -} - -func (x *DefineFieldStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineFieldStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineFieldStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - case "Perms": - if yyxt9 := z.Extension(x.Perms); yyxt9 != nil { - z.DecExtension(&x.Perms, yyxt9) - } else { - z.DecFallback(&x.Perms, true) - } - case "Type": - x.Type = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "Kind": - x.Kind = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "Value": - if yyxt13 := z.Extension(x.Value); yyxt13 != nil { - z.DecExtension(&x.Value, yyxt13) - } else { - z.DecFallback(&x.Value, true) - } - case "Assert": - if yyxt15 := z.Extension(x.Assert); yyxt15 != nil { - z.DecExtension(&x.Assert, yyxt15) - } else { - z.DecFallback(&x.Assert, true) - } - case "Priority": - x.Priority = (float64)(r.DecodeFloat64()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineFieldStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj17 int - var yyb17 bool - var yyhl17 bool = l >= 0 - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt19 := z.Extension(x.Name); yyxt19 != nil { - z.DecExtension(x.Name, yyxt19) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt21 := z.Extension(x.What); yyxt21 != nil { - z.DecExtension(&x.What, yyxt21) - } else { - x.What.CodecDecodeSelf(d) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt23 := z.Extension(x.Perms); yyxt23 != nil { - z.DecExtension(&x.Perms, yyxt23) - } else { - z.DecFallback(&x.Perms, true) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Type = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Kind = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt27 := z.Extension(x.Value); yyxt27 != nil { - z.DecExtension(&x.Value, yyxt27) - } else { - z.DecFallback(&x.Value, true) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt29 := z.Extension(x.Assert); yyxt29 != nil { - z.DecExtension(&x.Assert, yyxt29) - } else { - z.DecFallback(&x.Assert, true) - } - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Priority = (float64)(r.DecodeFloat64()) - for { - yyj17++ - if yyhl17 { - yyb17 = yyj17 > l - } else { - yyb17 = z.DecCheckBreak() - } - if yyb17 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj17-1, "") - } -} - -func (x *DefineFieldStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || x.Perms != nil || x.Type != "" || x.Kind != "" || x.Value != nil || x.Assert != nil || x.Priority != 0 || false) -} - -func (RemoveFieldStatement) codecSelferViaCodecgen() {} -func (x *RemoveFieldStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveFieldStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveFieldStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveFieldStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveFieldStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt10 := z.Extension(x.Name); yyxt10 != nil { - z.DecExtension(x.Name, yyxt10) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.DecExtension(&x.What, yyxt12) - } else { - x.What.CodecDecodeSelf(d) - } - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *RemoveFieldStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || false) -} - -func (DefineIndexStatement) codecSelferViaCodecgen() {} -func (x *DefineIndexStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Cols); yyxt9 != nil { - z.EncExtension(x.Cols, yyxt9) - } else { - x.Cols.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Uniq)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt11 := z.Extension(x.Name); yyxt11 != nil { - z.EncExtension(x.Name, yyxt11) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.EncExtension(x.What, yyxt12) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cols\"") - } else { - r.EncodeString(`Cols`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Cols); yyxt13 != nil { - z.EncExtension(x.Cols, yyxt13) - } else { - x.Cols.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Uniq\"") - } else { - r.EncodeString(`Uniq`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Uniq)) - z.EncWriteMapEnd() - } - } -} - -func (x *DefineIndexStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DefineIndexStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DefineIndexStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - case "Cols": - if yyxt9 := z.Extension(x.Cols); yyxt9 != nil { - z.DecExtension(&x.Cols, yyxt9) - } else { - x.Cols.CodecDecodeSelf(d) - } - case "Uniq": - x.Uniq = (bool)(r.DecodeBool()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DefineIndexStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj11 int - var yyb11 bool - var yyhl11 bool = l >= 0 - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt13 := z.Extension(x.Name); yyxt13 != nil { - z.DecExtension(x.Name, yyxt13) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt15 := z.Extension(x.What); yyxt15 != nil { - z.DecExtension(&x.What, yyxt15) - } else { - x.What.CodecDecodeSelf(d) - } - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt17 := z.Extension(x.Cols); yyxt17 != nil { - z.DecExtension(&x.Cols, yyxt17) - } else { - x.Cols.CodecDecodeSelf(d) - } - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Uniq = (bool)(r.DecodeBool()) - for { - yyj11++ - if yyhl11 { - yyb11 = yyj11 > l - } else { - yyb11 = z.DecCheckBreak() - } - if yyb11 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj11-1, "") - } -} - -func (x *DefineIndexStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || len(x.Cols) != 0 || bool(x.Uniq) || false) -} - -func (RemoveIndexStatement) codecSelferViaCodecgen() {} -func (x *RemoveIndexStatement) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.EncExtension(x.Name, yyxt5) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt8 := z.Extension(x.What); yyxt8 != nil { - z.EncExtension(x.What, yyxt8) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *RemoveIndexStatement) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = RemoveIndexStatement{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *RemoveIndexStatement) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt5 := z.Extension(x.Name); yyxt5 != nil { - z.DecExtension(x.Name, yyxt5) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "What": - if yyxt7 := z.Extension(x.What); yyxt7 != nil { - z.DecExtension(&x.What, yyxt7) - } else { - x.What.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *RemoveIndexStatement) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt10 := z.Extension(x.Name); yyxt10 != nil { - z.DecExtension(x.Name, yyxt10) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.DecExtension(&x.What, yyxt12) - } else { - x.What.CodecDecodeSelf(d) - } - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *RemoveIndexStatement) IsCodecEmpty() bool { - return !(len(x.What) != 0 || false) -} - -func (Exprs) codecSelferViaCodecgen() {} -func (x Exprs) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encExprs((Exprs)(x), e) - } // end block: if x slice == nil -} - -func (x *Exprs) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decExprs((*Exprs)(x), d) -} - -func (All) codecSelferViaCodecgen() {} -func (x *All) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *All) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = All{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *All) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *All) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *All) IsCodecEmpty() bool { - return !(false) -} - -func (Any) codecSelferViaCodecgen() {} -func (x *Any) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *Any) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Any{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Any) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Any) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *Any) IsCodecEmpty() bool { - return !(false) -} - -func (Null) codecSelferViaCodecgen() {} -func (x *Null) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *Null) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Null{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Null) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Null) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *Null) IsCodecEmpty() bool { - return !(false) -} - -func (Void) codecSelferViaCodecgen() {} -func (x *Void) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *Void) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Void{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Void) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Void) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *Void) IsCodecEmpty() bool { - return !(false) -} - -func (Empty) codecSelferViaCodecgen() {} -func (x *Empty) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(0) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(0) - z.EncWriteMapEnd() - } - } -} - -func (x *Empty) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Empty{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Empty) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Empty) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj4 int - var yyb4 bool - var yyhl4 bool = l >= 0 - for { - yyj4++ - if yyhl4 { - yyb4 = yyj4 > l - } else { - yyb4 = z.DecCheckBreak() - } - if yyb4 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj4-1, "") - } -} - -func (x *Empty) IsCodecEmpty() bool { - return !(false) -} - -func (Field) codecSelferViaCodecgen() {} -func (x *Field) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.Expr); yyxt6 != nil { - z.EncExtension(x.Expr, yyxt6) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteArrayElem() - r.EncodeString(string(x.Field)) - z.EncWriteArrayElem() - r.EncodeString(string(x.Alias)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt9 := z.Extension(x.Expr); yyxt9 != nil { - z.EncExtension(x.Expr, yyxt9) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Field\"") - } else { - r.EncodeString(`Field`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Field)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Alias\"") - } else { - r.EncodeString(`Alias`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Alias)) - z.EncWriteMapEnd() - } - } -} - -func (x *Field) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Field{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Field) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.DecExtension(&x.Expr, yyxt5) - } else { - z.DecFallback(&x.Expr, true) - } - case "Field": - x.Field = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "Alias": - x.Alias = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Field) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt10 := z.Extension(x.Expr); yyxt10 != nil { - z.DecExtension(&x.Expr, yyxt10) - } else { - z.DecFallback(&x.Expr, true) - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Field = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Alias = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *Field) IsCodecEmpty() bool { - return !(x.Expr != nil || x.Field != "" || x.Alias != "" || false) -} - -func (Fields) codecSelferViaCodecgen() {} -func (x Fields) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encFields((Fields)(x), e) - } // end block: if x slice == nil -} - -func (x *Fields) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decFields((*Fields)(x), d) -} - -func (Group) codecSelferViaCodecgen() {} -func (x *Group) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Expr); yyxt4 != nil { - z.EncExtension(x.Expr, yyxt4) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.EncExtension(x.Expr, yyxt5) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteMapEnd() - } - } -} - -func (x *Group) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Group{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Group) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.DecExtension(&x.Expr, yyxt5) - } else { - z.DecFallback(&x.Expr, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Group) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Expr); yyxt8 != nil { - z.DecExtension(&x.Expr, yyxt8) - } else { - z.DecFallback(&x.Expr, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *Group) IsCodecEmpty() bool { - return !(x.Expr != nil || false) -} - -func (Groups) codecSelferViaCodecgen() {} -func (x Groups) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encGroups((Groups)(x), e) - } // end block: if x slice == nil -} - -func (x *Groups) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decGroups((*Groups)(x), d) -} - -func (Order) codecSelferViaCodecgen() {} -func (x *Order) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.Expr); yyxt6 != nil { - z.EncExtension(x.Expr, yyxt6) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Dir)) - z.EncWriteArrayElem() - yy8 := &x.Tag - if yyxt9 := z.Extension(yy8); yyxt9 != nil { - z.EncExtension(yy8, yyxt9) - } else if !z.EncBinary() { - z.EncTextMarshal(*yy8) - } else { - z.EncFallback(yy8) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt10 := z.Extension(x.Expr); yyxt10 != nil { - z.EncExtension(x.Expr, yyxt10) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Dir\"") - } else { - r.EncodeString(`Dir`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Dir)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Tag\"") - } else { - r.EncodeString(`Tag`) - } - z.EncWriteMapElemValue() - yy12 := &x.Tag - if yyxt13 := z.Extension(yy12); yyxt13 != nil { - z.EncExtension(yy12, yyxt13) - } else if !z.EncBinary() { - z.EncTextMarshal(*yy12) - } else { - z.EncFallback(yy12) - } - z.EncWriteMapEnd() - } - } -} - -func (x *Order) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Order{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Order) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.DecExtension(&x.Expr, yyxt5) - } else { - z.DecFallback(&x.Expr, true) - } - case "Dir": - x.Dir = (bool)(r.DecodeBool()) - case "Tag": - if yyxt8 := z.Extension(x.Tag); yyxt8 != nil { - z.DecExtension(&x.Tag, yyxt8) - } else if !z.DecBinary() { - z.DecTextUnmarshal(&x.Tag) - } else { - z.DecFallback(&x.Tag, false) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Order) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj9 int - var yyb9 bool - var yyhl9 bool = l >= 0 - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt11 := z.Extension(x.Expr); yyxt11 != nil { - z.DecExtension(&x.Expr, yyxt11) - } else { - z.DecFallback(&x.Expr, true) - } - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Dir = (bool)(r.DecodeBool()) - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Tag); yyxt14 != nil { - z.DecExtension(&x.Tag, yyxt14) - } else if !z.DecBinary() { - z.DecTextUnmarshal(&x.Tag) - } else { - z.DecFallback(&x.Tag, false) - } - for { - yyj9++ - if yyhl9 { - yyb9 = yyj9 > l - } else { - yyb9 = z.DecCheckBreak() - } - if yyb9 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj9-1, "") - } -} - -func (x *Order) IsCodecEmpty() bool { - return !(x.Expr != nil || bool(x.Dir) || x.Tag != pkg1_language.Tag{} || false) -} - -func (Orders) codecSelferViaCodecgen() {} -func (x Orders) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encOrders((Orders)(x), e) - } // end block: if x slice == nil -} - -func (x *Orders) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decOrders((*Orders)(x), d) -} - -func (Fetch) codecSelferViaCodecgen() {} -func (x *Fetch) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Expr); yyxt4 != nil { - z.EncExtension(x.Expr, yyxt4) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.EncExtension(x.Expr, yyxt5) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteMapEnd() - } - } -} - -func (x *Fetch) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Fetch{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Fetch) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.DecExtension(&x.Expr, yyxt5) - } else { - z.DecFallback(&x.Expr, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Fetch) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Expr); yyxt8 != nil { - z.DecExtension(&x.Expr, yyxt8) - } else { - z.DecFallback(&x.Expr, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *Fetch) IsCodecEmpty() bool { - return !(x.Expr != nil || false) -} - -func (Fetchs) codecSelferViaCodecgen() {} -func (x Fetchs) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encFetchs((Fetchs)(x), e) - } // end block: if x slice == nil -} - -func (x *Fetchs) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decFetchs((*Fetchs)(x), d) -} - -func (SubExpression) codecSelferViaCodecgen() {} -func (x *SubExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Expr); yyxt4 != nil { - z.EncExtension(x.Expr, yyxt4) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.EncExtension(x.Expr, yyxt5) - } else { - z.EncFallback(x.Expr) - } - z.EncWriteMapEnd() - } - } -} - -func (x *SubExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = SubExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *SubExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.DecExtension(&x.Expr, yyxt5) - } else { - z.DecFallback(&x.Expr, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *SubExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Expr); yyxt8 != nil { - z.DecExtension(&x.Expr, yyxt8) - } else { - z.DecFallback(&x.Expr, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *SubExpression) IsCodecEmpty() bool { - return !(x.Expr != nil || false) -} - -func (MultExpression) codecSelferViaCodecgen() {} -func (x *MultExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if x.Expr == nil { - r.EncodeNil() - } else { - h.encSliceExpr(([]Expr)(x.Expr), e) - } // end block: if x.Expr slice == nil - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if x.Expr == nil { - r.EncodeNil() - } else { - h.encSliceExpr(([]Expr)(x.Expr), e) - } // end block: if x.Expr slice == nil - z.EncWriteMapEnd() - } - } -} - -func (x *MultExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = MultExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *MultExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - h.decSliceExpr((*[]Expr)(&x.Expr), d) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *MultExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - h.decSliceExpr((*[]Expr)(&x.Expr), d) - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *MultExpression) IsCodecEmpty() bool { - return !(len(x.Expr) != 0 || false) -} - -func (FuncExpression) codecSelferViaCodecgen() {} -func (x *FuncExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - r.EncodeString(string(x.Name)) - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Args); yyxt7 != nil { - z.EncExtension(x.Args, yyxt7) - } else { - x.Args.CodecEncodeSelf(e) - } - z.EncWriteArrayElem() - r.EncodeBool(bool(x.Aggr)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.Name)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Args\"") - } else { - r.EncodeString(`Args`) - } - z.EncWriteMapElemValue() - if yyxt10 := z.Extension(x.Args); yyxt10 != nil { - z.EncExtension(x.Args, yyxt10) - } else { - x.Args.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Aggr\"") - } else { - r.EncodeString(`Aggr`) - } - z.EncWriteMapElemValue() - r.EncodeBool(bool(x.Aggr)) - z.EncWriteMapEnd() - } - } -} - -func (x *FuncExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = FuncExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *FuncExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Name": - x.Name = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "Args": - if yyxt6 := z.Extension(x.Args); yyxt6 != nil { - z.DecExtension(&x.Args, yyxt6) - } else { - x.Args.CodecDecodeSelf(d) - } - case "Aggr": - x.Aggr = (bool)(r.DecodeBool()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *FuncExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Name = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt11 := z.Extension(x.Args); yyxt11 != nil { - z.DecExtension(&x.Args, yyxt11) - } else { - x.Args.CodecDecodeSelf(d) - } - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.Aggr = (bool)(r.DecodeBool()) - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *FuncExpression) IsCodecEmpty() bool { - return !(x.Name != "" || len(x.Args) != 0 || bool(x.Aggr) || false) -} - -func (ItemExpression) codecSelferViaCodecgen() {} -func (x *ItemExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.LHS); yyxt6 != nil { - z.EncExtension(x.LHS, yyxt6) - } else { - z.EncFallback(x.LHS) - } - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Op); yyxt7 != nil { - z.EncExtension(x.Op, yyxt7) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Op) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Op) - } else { - r.EncodeInt(int64(x.Op)) - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.RHS); yyxt8 != nil { - z.EncExtension(x.RHS, yyxt8) - } else { - z.EncFallback(x.RHS) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"LHS\"") - } else { - r.EncodeString(`LHS`) - } - z.EncWriteMapElemValue() - if yyxt9 := z.Extension(x.LHS); yyxt9 != nil { - z.EncExtension(x.LHS, yyxt9) - } else { - z.EncFallback(x.LHS) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Op\"") - } else { - r.EncodeString(`Op`) - } - z.EncWriteMapElemValue() - if yyxt10 := z.Extension(x.Op); yyxt10 != nil { - z.EncExtension(x.Op, yyxt10) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Op) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Op) - } else { - r.EncodeInt(int64(x.Op)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RHS\"") - } else { - r.EncodeString(`RHS`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.RHS); yyxt11 != nil { - z.EncExtension(x.RHS, yyxt11) - } else { - z.EncFallback(x.RHS) - } - z.EncWriteMapEnd() - } - } -} - -func (x *ItemExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = ItemExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *ItemExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "LHS": - if yyxt5 := z.Extension(x.LHS); yyxt5 != nil { - z.DecExtension(&x.LHS, yyxt5) - } else { - z.DecFallback(&x.LHS, true) - } - case "Op": - if yyxt7 := z.Extension(x.Op); yyxt7 != nil { - z.DecExtension(&x.Op, yyxt7) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Op) - } else { - x.Op = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "RHS": - if yyxt9 := z.Extension(x.RHS); yyxt9 != nil { - z.DecExtension(&x.RHS, yyxt9) - } else { - z.DecFallback(&x.RHS, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *ItemExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj10 int - var yyb10 bool - var yyhl10 bool = l >= 0 - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.LHS); yyxt12 != nil { - z.DecExtension(&x.LHS, yyxt12) - } else { - z.DecFallback(&x.LHS, true) - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Op); yyxt14 != nil { - z.DecExtension(&x.Op, yyxt14) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Op) - } else { - x.Op = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.RHS); yyxt16 != nil { - z.DecExtension(&x.RHS, yyxt16) - } else { - z.DecFallback(&x.RHS, true) - } - for { - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj10-1, "") - } -} - -func (x *ItemExpression) IsCodecEmpty() bool { - return !(x.LHS != nil || x.Op != 0 || x.RHS != nil || false) -} - -func (BinaryExpression) codecSelferViaCodecgen() {} -func (x *BinaryExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.LHS); yyxt6 != nil { - z.EncExtension(x.LHS, yyxt6) - } else { - z.EncFallback(x.LHS) - } - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Op); yyxt7 != nil { - z.EncExtension(x.Op, yyxt7) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Op) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Op) - } else { - r.EncodeInt(int64(x.Op)) - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.RHS); yyxt8 != nil { - z.EncExtension(x.RHS, yyxt8) - } else { - z.EncFallback(x.RHS) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"LHS\"") - } else { - r.EncodeString(`LHS`) - } - z.EncWriteMapElemValue() - if yyxt9 := z.Extension(x.LHS); yyxt9 != nil { - z.EncExtension(x.LHS, yyxt9) - } else { - z.EncFallback(x.LHS) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Op\"") - } else { - r.EncodeString(`Op`) - } - z.EncWriteMapElemValue() - if yyxt10 := z.Extension(x.Op); yyxt10 != nil { - z.EncExtension(x.Op, yyxt10) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Op) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Op) - } else { - r.EncodeInt(int64(x.Op)) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RHS\"") - } else { - r.EncodeString(`RHS`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.RHS); yyxt11 != nil { - z.EncExtension(x.RHS, yyxt11) - } else { - z.EncFallback(x.RHS) - } - z.EncWriteMapEnd() - } - } -} - -func (x *BinaryExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = BinaryExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *BinaryExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "LHS": - if yyxt5 := z.Extension(x.LHS); yyxt5 != nil { - z.DecExtension(&x.LHS, yyxt5) - } else { - z.DecFallback(&x.LHS, true) - } - case "Op": - if yyxt7 := z.Extension(x.Op); yyxt7 != nil { - z.DecExtension(&x.Op, yyxt7) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Op) - } else { - x.Op = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - case "RHS": - if yyxt9 := z.Extension(x.RHS); yyxt9 != nil { - z.DecExtension(&x.RHS, yyxt9) - } else { - z.DecFallback(&x.RHS, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *BinaryExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj10 int - var yyb10 bool - var yyhl10 bool = l >= 0 - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.LHS); yyxt12 != nil { - z.DecExtension(&x.LHS, yyxt12) - } else { - z.DecFallback(&x.LHS, true) - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Op); yyxt14 != nil { - z.DecExtension(&x.Op, yyxt14) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Op) - } else { - x.Op = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.RHS); yyxt16 != nil { - z.DecExtension(&x.RHS, yyxt16) - } else { - z.DecFallback(&x.RHS, true) - } - for { - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj10-1, "") - } -} - -func (x *BinaryExpression) IsCodecEmpty() bool { - return !(x.LHS != nil || x.Op != 0 || x.RHS != nil || false) -} - -func (PathExpression) codecSelferViaCodecgen() {} -func (x *PathExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Expr); yyxt4 != nil { - z.EncExtension(x.Expr, yyxt4) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Expr\"") - } else { - r.EncodeString(`Expr`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.EncExtension(x.Expr, yyxt5) - } else { - x.Expr.CodecEncodeSelf(e) - } - z.EncWriteMapEnd() - } - } -} - -func (x *PathExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = PathExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *PathExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Expr": - if yyxt5 := z.Extension(x.Expr); yyxt5 != nil { - z.DecExtension(&x.Expr, yyxt5) - } else { - x.Expr.CodecDecodeSelf(d) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *PathExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Expr); yyxt8 != nil { - z.DecExtension(&x.Expr, yyxt8) - } else { - x.Expr.CodecDecodeSelf(d) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *PathExpression) IsCodecEmpty() bool { - return !(len(x.Expr) != 0 || false) -} - -func (PartExpression) codecSelferViaCodecgen() {} -func (x *PartExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Part); yyxt4 != nil { - z.EncExtension(x.Part, yyxt4) - } else { - z.EncFallback(x.Part) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Part\"") - } else { - r.EncodeString(`Part`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Part); yyxt5 != nil { - z.EncExtension(x.Part, yyxt5) - } else { - z.EncFallback(x.Part) - } - z.EncWriteMapEnd() - } - } -} - -func (x *PartExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = PartExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *PartExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Part": - if yyxt5 := z.Extension(x.Part); yyxt5 != nil { - z.DecExtension(&x.Part, yyxt5) - } else { - z.DecFallback(&x.Part, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *PartExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Part); yyxt8 != nil { - z.DecExtension(&x.Part, yyxt8) - } else { - z.DecFallback(&x.Part, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *PartExpression) IsCodecEmpty() bool { - return !(x.Part != nil || false) -} - -func (JoinExpression) codecSelferViaCodecgen() {} -func (x *JoinExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Join); yyxt4 != nil { - z.EncExtension(x.Join, yyxt4) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Join) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Join) - } else { - r.EncodeInt(int64(x.Join)) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Join\"") - } else { - r.EncodeString(`Join`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Join); yyxt5 != nil { - z.EncExtension(x.Join, yyxt5) - } else if z.EncBinary() { - z.EncBinaryMarshal(x.Join) - } else if !z.EncBinary() { - z.EncTextMarshal(x.Join) - } else { - r.EncodeInt(int64(x.Join)) - } - z.EncWriteMapEnd() - } - } -} - -func (x *JoinExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = JoinExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *JoinExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Join": - if yyxt5 := z.Extension(x.Join); yyxt5 != nil { - z.DecExtension(&x.Join, yyxt5) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Join) - } else { - x.Join = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *JoinExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Join); yyxt8 != nil { - z.DecExtension(&x.Join, yyxt8) - } else if z.DecBinary() { - z.DecBinaryUnmarshal(&x.Join) - } else { - x.Join = (Token)(z.C.IntV(r.DecodeInt64(), 16)) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *JoinExpression) IsCodecEmpty() bool { - return !(x.Join != 0 || false) -} - -func (SubpExpression) codecSelferViaCodecgen() {} -func (x *SubpExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn4 bool = x.Name == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(3) - z.EncWriteArrayElem() - if yyxt6 := z.Extension(x.What); yyxt6 != nil { - z.EncExtension(x.What, yyxt6) - } else { - x.What.CodecEncodeSelf(e) - } - if yyn4 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.EncExtension(x.Name, yyxt7) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Cond); yyxt8 != nil { - z.EncExtension(x.Cond, yyxt8) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(3) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"What\"") - } else { - r.EncodeString(`What`) - } - z.EncWriteMapElemValue() - if yyxt9 := z.Extension(x.What); yyxt9 != nil { - z.EncExtension(x.What, yyxt9) - } else { - x.What.CodecEncodeSelf(e) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Name\"") - } else { - r.EncodeString(`Name`) - } - z.EncWriteMapElemValue() - if yyn4 { - r.EncodeNil() - } else { - if yyxt10 := z.Extension(x.Name); yyxt10 != nil { - z.EncExtension(x.Name, yyxt10) - } else { - x.Name.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Cond\"") - } else { - r.EncodeString(`Cond`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.Cond); yyxt11 != nil { - z.EncExtension(x.Cond, yyxt11) - } else { - z.EncFallback(x.Cond) - } - z.EncWriteMapEnd() - } - } -} - -func (x *SubpExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = SubpExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *SubpExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "What": - if yyxt5 := z.Extension(x.What); yyxt5 != nil { - z.DecExtension(&x.What, yyxt5) - } else { - x.What.CodecDecodeSelf(d) - } - case "Name": - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt7 := z.Extension(x.Name); yyxt7 != nil { - z.DecExtension(x.Name, yyxt7) - } else { - x.Name.CodecDecodeSelf(d) - } - } - case "Cond": - if yyxt9 := z.Extension(x.Cond); yyxt9 != nil { - z.DecExtension(&x.Cond, yyxt9) - } else { - z.DecFallback(&x.Cond, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *SubpExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj10 int - var yyb10 bool - var yyhl10 bool = l >= 0 - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt12 := z.Extension(x.What); yyxt12 != nil { - z.DecExtension(&x.What, yyxt12) - } else { - x.What.CodecDecodeSelf(d) - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.Name != nil { // remove the if-true - x.Name = nil - } - } else { - if x.Name == nil { - x.Name = new(Ident) - } - if yyxt14 := z.Extension(x.Name); yyxt14 != nil { - z.DecExtension(x.Name, yyxt14) - } else { - x.Name.CodecDecodeSelf(d) - } - } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.Cond); yyxt16 != nil { - z.DecExtension(&x.Cond, yyxt16) - } else { - z.DecFallback(&x.Cond, true) - } - for { - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l - } else { - yyb10 = z.DecCheckBreak() - } - if yyb10 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj10-1, "") - } -} - -func (x *SubpExpression) IsCodecEmpty() bool { - return !(len(x.What) != 0 || x.Cond != nil || false) -} - -func (PermExpression) codecSelferViaCodecgen() {} -func (x *PermExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - if yyxt7 := z.Extension(x.Select); yyxt7 != nil { - z.EncExtension(x.Select, yyxt7) - } else { - z.EncFallback(x.Select) - } - z.EncWriteArrayElem() - if yyxt8 := z.Extension(x.Create); yyxt8 != nil { - z.EncExtension(x.Create, yyxt8) - } else { - z.EncFallback(x.Create) - } - z.EncWriteArrayElem() - if yyxt9 := z.Extension(x.Update); yyxt9 != nil { - z.EncExtension(x.Update, yyxt9) - } else { - z.EncFallback(x.Update) - } - z.EncWriteArrayElem() - if yyxt10 := z.Extension(x.Delete); yyxt10 != nil { - z.EncExtension(x.Delete, yyxt10) - } else { - z.EncFallback(x.Delete) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Select\"") - } else { - r.EncodeString(`Select`) - } - z.EncWriteMapElemValue() - if yyxt11 := z.Extension(x.Select); yyxt11 != nil { - z.EncExtension(x.Select, yyxt11) - } else { - z.EncFallback(x.Select) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Create\"") - } else { - r.EncodeString(`Create`) - } - z.EncWriteMapElemValue() - if yyxt12 := z.Extension(x.Create); yyxt12 != nil { - z.EncExtension(x.Create, yyxt12) - } else { - z.EncFallback(x.Create) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Update\"") - } else { - r.EncodeString(`Update`) - } - z.EncWriteMapElemValue() - if yyxt13 := z.Extension(x.Update); yyxt13 != nil { - z.EncExtension(x.Update, yyxt13) - } else { - z.EncFallback(x.Update) - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Delete\"") - } else { - r.EncodeString(`Delete`) - } - z.EncWriteMapElemValue() - if yyxt14 := z.Extension(x.Delete); yyxt14 != nil { - z.EncExtension(x.Delete, yyxt14) - } else { - z.EncFallback(x.Delete) - } - z.EncWriteMapEnd() - } - } -} - -func (x *PermExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = PermExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *PermExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Select": - if yyxt5 := z.Extension(x.Select); yyxt5 != nil { - z.DecExtension(&x.Select, yyxt5) - } else { - z.DecFallback(&x.Select, true) - } - case "Create": - if yyxt7 := z.Extension(x.Create); yyxt7 != nil { - z.DecExtension(&x.Create, yyxt7) - } else { - z.DecFallback(&x.Create, true) - } - case "Update": - if yyxt9 := z.Extension(x.Update); yyxt9 != nil { - z.DecExtension(&x.Update, yyxt9) - } else { - z.DecFallback(&x.Update, true) - } - case "Delete": - if yyxt11 := z.Extension(x.Delete); yyxt11 != nil { - z.DecExtension(&x.Delete, yyxt11) - } else { - z.DecFallback(&x.Delete, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *PermExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj12 int - var yyb12 bool - var yyhl12 bool = l >= 0 - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt14 := z.Extension(x.Select); yyxt14 != nil { - z.DecExtension(&x.Select, yyxt14) - } else { - z.DecFallback(&x.Select, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt16 := z.Extension(x.Create); yyxt16 != nil { - z.DecExtension(&x.Create, yyxt16) - } else { - z.DecFallback(&x.Create, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt18 := z.Extension(x.Update); yyxt18 != nil { - z.DecExtension(&x.Update, yyxt18) - } else { - z.DecFallback(&x.Update, true) - } - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt20 := z.Extension(x.Delete); yyxt20 != nil { - z.DecExtension(&x.Delete, yyxt20) - } else { - z.DecFallback(&x.Delete, true) - } - for { - yyj12++ - if yyhl12 { - yyb12 = yyj12 > l - } else { - yyb12 = z.DecCheckBreak() - } - if yyb12 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj12-1, "") - } -} - -func (x *PermExpression) IsCodecEmpty() bool { - return !(x.Select != nil || x.Create != nil || x.Update != nil || x.Delete != nil || false) -} - -func (DataExpression) codecSelferViaCodecgen() {} -func (x *DataExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if x.Data == nil { - r.EncodeNil() - } else { - h.encSlicePtrtoItemExpression(([]*ItemExpression)(x.Data), e) - } // end block: if x.Data slice == nil - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if x.Data == nil { - r.EncodeNil() - } else { - h.encSlicePtrtoItemExpression(([]*ItemExpression)(x.Data), e) - } // end block: if x.Data slice == nil - z.EncWriteMapEnd() - } - } -} - -func (x *DataExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DataExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DataExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Data": - h.decSlicePtrtoItemExpression((*[]*ItemExpression)(&x.Data), d) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DataExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - h.decSlicePtrtoItemExpression((*[]*ItemExpression)(&x.Data), d) - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *DataExpression) IsCodecEmpty() bool { - return !(len(x.Data) != 0 || false) -} - -func (DiffExpression) codecSelferViaCodecgen() {} -func (x *DiffExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Data); yyxt4 != nil { - z.EncExtension(x.Data, yyxt4) - } else { - z.EncFallback(x.Data) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.EncExtension(x.Data, yyxt5) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapEnd() - } - } -} - -func (x *DiffExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = DiffExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *DiffExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Data": - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.DecExtension(&x.Data, yyxt5) - } else { - z.DecFallback(&x.Data, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *DiffExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Data); yyxt8 != nil { - z.DecExtension(&x.Data, yyxt8) - } else { - z.DecFallback(&x.Data, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *DiffExpression) IsCodecEmpty() bool { - return !(x.Data != nil || false) -} - -func (MergeExpression) codecSelferViaCodecgen() {} -func (x *MergeExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Data); yyxt4 != nil { - z.EncExtension(x.Data, yyxt4) - } else { - z.EncFallback(x.Data) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.EncExtension(x.Data, yyxt5) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapEnd() - } - } -} - -func (x *MergeExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = MergeExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *MergeExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Data": - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.DecExtension(&x.Data, yyxt5) - } else { - z.DecFallback(&x.Data, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *MergeExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Data); yyxt8 != nil { - z.DecExtension(&x.Data, yyxt8) - } else { - z.DecFallback(&x.Data, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *MergeExpression) IsCodecEmpty() bool { - return !(x.Data != nil || false) -} - -func (ContentExpression) codecSelferViaCodecgen() {} -func (x *ContentExpression) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if yyxt4 := z.Extension(x.Data); yyxt4 != nil { - z.EncExtension(x.Data, yyxt4) - } else { - z.EncFallback(x.Data) - } - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"Data\"") - } else { - r.EncodeString(`Data`) - } - z.EncWriteMapElemValue() - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.EncExtension(x.Data, yyxt5) - } else { - z.EncFallback(x.Data) - } - z.EncWriteMapEnd() - } - } -} - -func (x *ContentExpression) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = ContentExpression{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *ContentExpression) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "Data": - if yyxt5 := z.Extension(x.Data); yyxt5 != nil { - z.DecExtension(&x.Data, yyxt5) - } else { - z.DecFallback(&x.Data, true) - } - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *ContentExpression) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if yyxt8 := z.Extension(x.Data); yyxt8 != nil { - z.DecExtension(&x.Data, yyxt8) - } else { - z.DecFallback(&x.Data, true) - } - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *ContentExpression) IsCodecEmpty() bool { - return !(x.Data != nil || false) -} - -func (Params) codecSelferViaCodecgen() {} -func (x Params) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encParams((Params)(x), e) - } // end block: if x slice == nil -} - -func (x *Params) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decParams((*Params)(x), d) -} - -func (Param) codecSelferViaCodecgen() {} -func (x *Param) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - r.EncodeString(string(x.VA)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"VA\"") - } else { - r.EncodeString(`VA`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.VA)) - z.EncWriteMapEnd() - } - } -} - -func (x *Param) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Param{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Param) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "VA": - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Param) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj5 int - var yyb5 bool - var yyhl5 bool = l >= 0 - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj5-1, "") - } -} - -func (x *Param) IsCodecEmpty() bool { - return !(x.VA != "" || false) -} - -func (Idents) codecSelferViaCodecgen() {} -func (x Idents) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encIdents((Idents)(x), e) - } // end block: if x slice == nil -} - -func (x *Idents) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decIdents((*Idents)(x), d) -} - -func (Ident) codecSelferViaCodecgen() {} -func (x *Ident) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - r.EncodeString(string(x.VA)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"VA\"") - } else { - r.EncodeString(`VA`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.VA)) - z.EncWriteMapEnd() - } - } -} - -func (x *Ident) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Ident{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Ident) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "VA": - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Ident) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj5 int - var yyb5 bool - var yyhl5 bool = l >= 0 - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj5-1, "") - } -} - -func (x *Ident) IsCodecEmpty() bool { - return !(x.VA != "" || false) -} - -func (Values) codecSelferViaCodecgen() {} -func (x Values) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encValues((Values)(x), e) - } // end block: if x slice == nil -} - -func (x *Values) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decValues((*Values)(x), d) -} - -func (Value) codecSelferViaCodecgen() {} -func (x *Value) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - r.EncodeString(string(x.VA)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"VA\"") - } else { - r.EncodeString(`VA`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.VA)) - z.EncWriteMapEnd() - } - } -} - -func (x *Value) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Value{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Value) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "VA": - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Value) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj5 int - var yyb5 bool - var yyhl5 bool = l >= 0 - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj5-1, "") - } -} - -func (x *Value) IsCodecEmpty() bool { - return !(x.VA != "" || false) -} - -func (Regexs) codecSelferViaCodecgen() {} -func (x Regexs) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encRegexs((Regexs)(x), e) - } // end block: if x slice == nil -} - -func (x *Regexs) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decRegexs((*Regexs)(x), d) -} - -func (Regex) codecSelferViaCodecgen() {} -func (x *Regex) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - r.EncodeString(string(x.VA)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"VA\"") - } else { - r.EncodeString(`VA`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.VA)) - z.EncWriteMapEnd() - } - } -} - -func (x *Regex) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Regex{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Regex) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "VA": - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Regex) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj5 int - var yyb5 bool - var yyhl5 bool = l >= 0 - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.VA = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj5-1, "") - } -} - -func (x *Regex) IsCodecEmpty() bool { - return !(x.VA != "" || false) -} - -func (Tables) codecSelferViaCodecgen() {} -func (x Tables) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encTables((Tables)(x), e) - } // end block: if x slice == nil -} - -func (x *Tables) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decTables((*Tables)(x), d) -} - -func (Table) codecSelferViaCodecgen() {} -func (x *Table) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - r.EncodeString(string(x.TB)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"TB\"") - } else { - r.EncodeString(`TB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.TB)) - z.EncWriteMapEnd() - } - } -} - -func (x *Table) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Table{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Table) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "TB": - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Table) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj5 int - var yyb5 bool - var yyhl5 bool = l >= 0 - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - for { - yyj5++ - if yyhl5 { - yyb5 = yyj5 > l - } else { - yyb5 = z.DecCheckBreak() - } - if yyb5 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj5-1, "") - } -} - -func (x *Table) IsCodecEmpty() bool { - return !(x.TB != "" || false) -} - -func (Batchs) codecSelferViaCodecgen() {} -func (x Batchs) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encBatchs((Batchs)(x), e) - } // end block: if x slice == nil -} - -func (x *Batchs) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decBatchs((*Batchs)(x), d) -} - -func (Batch) codecSelferViaCodecgen() {} -func (x *Batch) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeString(string(x.TB)) - z.EncWriteArrayElem() - if x.BA == nil { - r.EncodeNil() - } else { - h.encSlicePtrtoThing(([]*Thing)(x.BA), e) - } // end block: if x.BA slice == nil - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"TB\"") - } else { - r.EncodeString(`TB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.TB)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"BA\"") - } else { - r.EncodeString(`BA`) - } - z.EncWriteMapElemValue() - if x.BA == nil { - r.EncodeNil() - } else { - h.encSlicePtrtoThing(([]*Thing)(x.BA), e) - } // end block: if x.BA slice == nil - z.EncWriteMapEnd() - } - } -} - -func (x *Batch) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Batch{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Batch) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "TB": - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "BA": - h.decSlicePtrtoThing((*[]*Thing)(&x.BA), d) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Batch) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - h.decSlicePtrtoThing((*[]*Thing)(&x.BA), d) - for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj7-1, "") - } -} - -func (x *Batch) IsCodecEmpty() bool { - return !(x.TB != "" || len(x.BA) != 0 || false) -} - -func (Models) codecSelferViaCodecgen() {} -func (x Models) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encModels((Models)(x), e) - } // end block: if x slice == nil -} - -func (x *Models) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decModels((*Models)(x), d) -} - -func (Model) codecSelferViaCodecgen() {} -func (x *Model) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(4) - z.EncWriteArrayElem() - r.EncodeString(string(x.TB)) - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.MIN)) - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.INC)) - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.MAX)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(4) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"TB\"") - } else { - r.EncodeString(`TB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.TB)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"MIN\"") - } else { - r.EncodeString(`MIN`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.MIN)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"INC\"") - } else { - r.EncodeString(`INC`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.INC)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"MAX\"") - } else { - r.EncodeString(`MAX`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.MAX)) - z.EncWriteMapEnd() - } - } -} - -func (x *Model) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Model{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Model) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "TB": - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "MIN": - x.MIN = (float64)(r.DecodeFloat64()) - case "INC": - x.INC = (float64)(r.DecodeFloat64()) - case "MAX": - x.MAX = (float64)(r.DecodeFloat64()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Model) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj8 int - var yyb8 bool - var yyhl8 bool = l >= 0 - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.MIN = (float64)(r.DecodeFloat64()) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.INC = (float64)(r.DecodeFloat64()) - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.MAX = (float64)(r.DecodeFloat64()) - for { - yyj8++ - if yyhl8 { - yyb8 = yyj8 > l - } else { - yyb8 = z.DecCheckBreak() - } - if yyb8 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj8-1, "") - } -} - -func (x *Model) IsCodecEmpty() bool { - return !(x.TB != "" || x.MIN != 0 || x.INC != 0 || x.MAX != 0 || false) -} - -func (Things) codecSelferViaCodecgen() {} -func (x Things) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encThings((Things)(x), e) - } // end block: if x slice == nil -} - -func (x *Things) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decThings((*Things)(x), d) -} - -func (Thing) codecSelferViaCodecgen() {} -func (x *Thing) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - if !z.EncBinary() { - z.EncTextMarshal(*x) - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeString(string(x.TB)) - z.EncWriteArrayElem() - z.EncFallback(x.ID) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"TB\"") - } else { - r.EncodeString(`TB`) - } - z.EncWriteMapElemValue() - r.EncodeString(string(x.TB)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"ID\"") - } else { - r.EncodeString(`ID`) - } - z.EncWriteMapElemValue() - z.EncFallback(x.ID) - z.EncWriteMapEnd() - } - } - } -} - -func (x *Thing) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Thing{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Thing) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "TB": - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - case "ID": - z.DecFallback(&x.ID, true) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Thing) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.TB = (string)(z.DecStringZC(r.DecodeStringAsBytes())) - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - z.DecFallback(&x.ID, true) - for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj7-1, "") - } -} - -func (x *Thing) IsCodecEmpty() bool { - return !(x.TB != "" || x.ID != nil || false) -} - -func (Points) codecSelferViaCodecgen() {} -func (x Points) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encPoints((Points)(x), e) - } // end block: if x slice == nil -} - -func (x *Points) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decPoints((*Points)(x), d) -} - -func (Point) codecSelferViaCodecgen() {} -func (x *Point) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - if !z.EncBinary() && z.IsJSONHandle() { - z.EncJSONMarshal(*x) - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.LO)) - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.LA)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"LO\"") - } else { - r.EncodeString(`LO`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.LO)) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"LA\"") - } else { - r.EncodeString(`LA`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.LA)) - z.EncWriteMapEnd() - } - } - } -} - -func (x *Point) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Point{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Point) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "LO": - x.LO = (float64)(r.DecodeFloat64()) - case "LA": - x.LA = (float64)(r.DecodeFloat64()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Point) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.LO = (float64)(r.DecodeFloat64()) - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.LA = (float64)(r.DecodeFloat64()) - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *Point) IsCodecEmpty() bool { - return !(x.LO != 0 || x.LA != 0 || false) -} - -func (Circles) codecSelferViaCodecgen() {} -func (x Circles) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encCircles((Circles)(x), e) - } // end block: if x slice == nil -} - -func (x *Circles) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decCircles((*Circles)(x), d) -} - -func (Circle) codecSelferViaCodecgen() {} -func (x *Circle) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - if !z.EncBinary() && z.IsJSONHandle() { - z.EncJSONMarshal(*x) - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - var yyn3 bool = x.CE == nil - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(2) - if yyn3 { - z.EncWriteArrayElem() - r.EncodeNil() - } else { - z.EncWriteArrayElem() - if yyxt5 := z.Extension(x.CE); yyxt5 != nil { - z.EncExtension(x.CE, yyxt5) - } else { - x.CE.CodecEncodeSelf(e) - } - } - z.EncWriteArrayElem() - r.EncodeFloat64(float64(x.RA)) - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(2) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"CE\"") - } else { - r.EncodeString(`CE`) - } - z.EncWriteMapElemValue() - if yyn3 { - r.EncodeNil() - } else { - if yyxt7 := z.Extension(x.CE); yyxt7 != nil { - z.EncExtension(x.CE, yyxt7) - } else { - x.CE.CodecEncodeSelf(e) - } - } - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"RA\"") - } else { - r.EncodeString(`RA`) - } - z.EncWriteMapElemValue() - r.EncodeFloat64(float64(x.RA)) - z.EncWriteMapEnd() - } - } - } -} - -func (x *Circle) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Circle{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Circle) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "CE": - if r.TryNil() { - if x.CE != nil { // remove the if-true - x.CE = nil - } - } else { - if x.CE == nil { - x.CE = new(Point) - } - if yyxt5 := z.Extension(x.CE); yyxt5 != nil { - z.DecExtension(x.CE, yyxt5) - } else { - x.CE.CodecDecodeSelf(d) - } - } - case "RA": - x.RA = (float64)(r.DecodeFloat64()) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Circle) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj7 int - var yyb7 bool - var yyhl7 bool = l >= 0 - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - if r.TryNil() { - if x.CE != nil { // remove the if-true - x.CE = nil - } - } else { - if x.CE == nil { - x.CE = new(Point) - } - if yyxt9 := z.Extension(x.CE); yyxt9 != nil { - z.DecExtension(x.CE, yyxt9) - } else { - x.CE.CodecDecodeSelf(d) - } - } - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - x.RA = (float64)(r.DecodeFloat64()) - for { - yyj7++ - if yyhl7 { - yyb7 = yyj7 > l - } else { - yyb7 = z.DecCheckBreak() - } - if yyb7 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj7-1, "") - } -} - -func (x *Circle) IsCodecEmpty() bool { - return !(x.RA != 0 || false) -} - -func (Polygons) codecSelferViaCodecgen() {} -func (x Polygons) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if x == nil { - r.EncodeNil() - } else { - h.encPolygons((Polygons)(x), e) - } // end block: if x slice == nil -} - -func (x *Polygons) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - h.decPolygons((*Polygons)(x), d) -} - -func (Polygon) codecSelferViaCodecgen() {} -func (x *Polygon) CodecEncodeSelf(e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if z.EncBasicHandle().CheckCircularRef { - z.EncEncode(x) - return - } - if x == nil { - r.EncodeNil() - } else { - if !z.EncBinary() && z.IsJSONHandle() { - z.EncJSONMarshal(*x) - } else { - yy2arr2 := z.EncBasicHandle().StructToArray - _ = yy2arr2 - const yyr2 bool = false // struct tag has 'toArray' - if yyr2 || yy2arr2 { - z.EncWriteArrayStart(1) - z.EncWriteArrayElem() - if x.PS == nil { - r.EncodeNil() - } else { - h.encSlicePtrtoPoint(([]*Point)(x.PS), e) - } // end block: if x.PS slice == nil - z.EncWriteArrayEnd() - } else { - z.EncWriteMapStart(1) - z.EncWriteMapElemKey() - if z.IsJSONHandle() { - z.WriteStr("\"PS\"") - } else { - r.EncodeString(`PS`) - } - z.EncWriteMapElemValue() - if x.PS == nil { - r.EncodeNil() - } else { - h.encSlicePtrtoPoint(([]*Point)(x.PS), e) - } // end block: if x.PS slice == nil - z.EncWriteMapEnd() - } - } - } -} - -func (x *Polygon) CodecDecodeSelf(d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - yyct2 := r.ContainerType() - if yyct2 == codecSelferValueTypeNil6263 { - *(x) = Polygon{} - } else if yyct2 == codecSelferValueTypeMap6263 { - yyl2 := z.DecReadMapStart() - if yyl2 == 0 { - } else { - x.codecDecodeSelfFromMap(yyl2, d) - } - z.DecReadMapEnd() - } else if yyct2 == codecSelferValueTypeArray6263 { - yyl2 := z.DecReadArrayStart() - if yyl2 != 0 { - x.codecDecodeSelfFromArray(yyl2, d) - } - z.DecReadArrayEnd() - } else { - panic(errCodecSelferOnlyMapOrArrayEncodeToStruct6263) - } -} - -func (x *Polygon) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyhl3 bool = l >= 0 - for yyj3 := 0; ; yyj3++ { - if yyhl3 { - if yyj3 >= l { - break - } - } else { - if z.DecCheckBreak() { - break - } - } - z.DecReadMapElemKey() - yys3 := r.DecodeStringAsBytes() - z.DecReadMapElemValue() - switch string(yys3) { - case "PS": - h.decSlicePtrtoPoint((*[]*Point)(&x.PS), d) - default: - z.DecStructFieldNotFound(-1, string(yys3)) - } // end switch yys3 - } // end for yyj3 -} - -func (x *Polygon) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - var yyj6 int - var yyb6 bool - var yyhl6 bool = l >= 0 - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - z.DecReadArrayEnd() - return - } - z.DecReadArrayElem() - h.decSlicePtrtoPoint((*[]*Point)(&x.PS), d) - for { - yyj6++ - if yyhl6 { - yyb6 = yyj6 > l - } else { - yyb6 = z.DecCheckBreak() - } - if yyb6 { - break - } - z.DecReadArrayElem() - z.DecStructFieldNotFound(yyj6-1, "") - } -} - -func (x *Polygon) IsCodecEmpty() bool { - return !(len(x.PS) != 0 || false) -} - -func (x codecSelfer6263) encStatements(v Statements, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - z.EncFallback(v[yyv1]) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decStatements(v *Statements, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []Statement{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]Statement, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) - } else { - yyrl1 = 8 - } - yyv1 = make([]Statement, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(&yyv1[yyj1], yyxt3) - } else { - z.DecFallback(&yyv1[yyj1], true) - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]Statement, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encExprs(v Exprs, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - z.EncFallback(v[yyv1]) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decExprs(v *Exprs, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []Expr{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]Expr, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) - } else { - yyrl1 = 8 - } - yyv1 = make([]Expr, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(&yyv1[yyj1], yyxt3) - } else { - z.DecFallback(&yyv1[yyj1], true) - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]Expr, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encFields(v Fields, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decFields(v *Fields, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Field{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Field, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Field, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Field) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Field, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encGroups(v Groups, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decGroups(v *Groups, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Group{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Group, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Group, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Group) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Group, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encOrders(v Orders, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decOrders(v *Orders, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Order{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Order, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Order, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Order) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Order, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encFetchs(v Fetchs, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decFetchs(v *Fetchs, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Fetch{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Fetch, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Fetch, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Fetch) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Fetch, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encSliceExpr(v []Expr, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - z.EncFallback(v[yyv1]) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decSliceExpr(v *[]Expr, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []Expr{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]Expr, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 16) - } else { - yyrl1 = 8 - } - yyv1 = make([]Expr, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(&yyv1[yyj1], yyxt3) - } else { - z.DecFallback(&yyv1[yyj1], true) - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]Expr, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encSlicePtrtoItemExpression(v []*ItemExpression, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decSlicePtrtoItemExpression(v *[]*ItemExpression, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*ItemExpression{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*ItemExpression, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*ItemExpression, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(ItemExpression) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*ItemExpression, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encParams(v Params, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decParams(v *Params, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Param{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Param, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Param, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Param) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Param, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encIdents(v Idents, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decIdents(v *Idents, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Ident{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Ident, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Ident, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Ident) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Ident, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encValues(v Values, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decValues(v *Values, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Value{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Value, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Value, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Value) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Value, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encRegexs(v Regexs, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decRegexs(v *Regexs, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Regex{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Regex, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Regex, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Regex) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Regex, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encTables(v Tables, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decTables(v *Tables, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Table{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Table, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Table, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Table) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Table, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encBatchs(v Batchs, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decBatchs(v *Batchs, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Batch{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Batch, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Batch, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Batch) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Batch, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encSlicePtrtoThing(v []*Thing, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decSlicePtrtoThing(v *[]*Thing, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Thing{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Thing, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Thing, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Thing) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Thing, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encModels(v Models, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decModels(v *Models, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Model{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Model, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Model, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Model) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Model, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encThings(v Things, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decThings(v *Things, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Thing{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Thing, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Thing, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Thing) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Thing, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encPoints(v Points, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decPoints(v *Points, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Point{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Point, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Point, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Point) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Point, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encCircles(v Circles, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decCircles(v *Circles, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Circle{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Circle, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Circle, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Circle) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Circle, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encPolygons(v Polygons, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decPolygons(v *Polygons, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Polygon{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Polygon, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Polygon, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Polygon) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Polygon, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} - -func (x codecSelfer6263) encSlicePtrtoPoint(v []*Point, e *codec1978.Encoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Encoder(e) - _, _, _ = h, z, r - if v == nil { - r.EncodeNil() - return - } - z.EncWriteArrayStart(len(v)) - for yyv1 := range v { - z.EncWriteArrayElem() - if v[yyv1] == nil { - r.EncodeNil() - } else { - if yyxt2 := z.Extension(v[yyv1]); yyxt2 != nil { - z.EncExtension(v[yyv1], yyxt2) - } else { - v[yyv1].CodecEncodeSelf(e) - } - } - } - z.EncWriteArrayEnd() -} - -func (x codecSelfer6263) decSlicePtrtoPoint(v *[]*Point, d *codec1978.Decoder) { - var h codecSelfer6263 - z, r := codec1978.GenHelper().Decoder(d) - _, _, _ = h, z, r - - yyv1 := *v - yyh1, yyl1 := z.DecSliceHelperStart() - var yyc1 bool - _ = yyc1 - if yyh1.IsNil { - if yyv1 != nil { - yyv1 = nil - yyc1 = true - } - } else if yyl1 == 0 { - if yyv1 == nil { - yyv1 = []*Point{} - yyc1 = true - } else if len(yyv1) != 0 { - yyv1 = yyv1[:0] - yyc1 = true - } - } else { - yyhl1 := yyl1 > 0 - var yyrl1 int - _ = yyrl1 - if yyhl1 { - if yyl1 > cap(yyv1) { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - if yyrl1 <= cap(yyv1) { - yyv1 = yyv1[:yyrl1] - } else { - yyv1 = make([]*Point, yyrl1) - } - yyc1 = true - } else if yyl1 != len(yyv1) { - yyv1 = yyv1[:yyl1] - yyc1 = true - } - } - var yyj1 int - for yyj1 = 0; (yyhl1 && yyj1 < yyl1) || !(yyhl1 || z.DecCheckBreak()); yyj1++ { // bounds-check-elimination - if yyj1 == 0 && yyv1 == nil { - if yyhl1 { - yyrl1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 8) - } else { - yyrl1 = 8 - } - yyv1 = make([]*Point, yyrl1) - yyc1 = true - } - yyh1.ElemContainerState(yyj1) - var yydb1 bool - if yyj1 >= len(yyv1) { - yyv1 = append(yyv1, nil) - yyc1 = true - } - if yydb1 { - z.DecSwallow() - } else { - if r.TryNil() { - yyv1[yyj1] = nil - } else { - if yyv1[yyj1] == nil { - yyv1[yyj1] = new(Point) - } - if yyxt3 := z.Extension(yyv1[yyj1]); yyxt3 != nil { - z.DecExtension(yyv1[yyj1], yyxt3) - } else { - yyv1[yyj1].CodecDecodeSelf(d) - } - } - } - } - if yyj1 < len(yyv1) { - yyv1 = yyv1[:yyj1] - yyc1 = true - } else if yyj1 == 0 && yyv1 == nil { - yyv1 = make([]*Point, 0) - yyc1 = true - } - } - yyh1.End() - if yyc1 { - *v = yyv1 - } -} diff --git a/sql/ast.go b/sql/ast.go deleted file mode 100644 index 96b9095c..00000000 --- a/sql/ast.go +++ /dev/null @@ -1,754 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "strconv" - "strings" - "time" - - "golang.org/x/text/language" -) - -// -------------------------------------------------- -// Queries -// -------------------------------------------------- - -// Query represents a multi statement SQL query -type Query struct { - Statements Statements -} - -// Statement represents a single SQL AST -type Statement interface{} - -// Statements represents multiple SQL ASTs -type Statements []Statement - -// -------------------------------------------------- -// Other -// -------------------------------------------------- - -type AuthableStatement interface { - Auth() (string, string) -} - -type KillableStatement interface { - Duration() time.Duration -} - -type WriteableStatement interface { - Writeable() bool -} - -// -------------------------------------------------- -// Use -// -------------------------------------------------- - -// UseStatement represents a SQL USE statement. -type UseStatement struct { - NS string - DB string -} - -// -------------------------------------------------- -// Options -// -------------------------------------------------- - -// OptStatement represents a SQL OPTION statement. -type OptStatement struct { - Name string - What bool -} - -// -------------------------------------------------- -// Trans -// -------------------------------------------------- - -// BeginStatement represents a SQL BEGIN TRANSACTION statement. -type BeginStatement struct{} - -// CancelStatement represents a SQL CANCEL TRANSACTION statement. -type CancelStatement struct{} - -// CommitStatement represents a SQL COMMIT TRANSACTION statement. -type CommitStatement struct{} - -// -------------------------------------------------- -// Info -// -------------------------------------------------- - -// InfoStatement represents an SQL INFO statement. -type InfoStatement struct { - Kind Token - What *Ident -} - -// -------------------------------------------------- -// Run -// -------------------------------------------------- - -// RunStatement represents a run clause. -type RunStatement struct { - RW bool - Expr Expr -} - -// -------------------------------------------------- -// Let -// -------------------------------------------------- - -// LetStatement represents a SQL LET statement. -type LetStatement struct { - RW bool - Name *Ident - What Expr -} - -// -------------------------------------------------- -// Live -// -------------------------------------------------- - -// LiveStatement represents a SQL LIVE statement. -type LiveStatement struct { - ID string - FB string - NS string - DB string - Diff bool - Expr Fields - What Exprs - Cond Expr - Fetch Fetchs -} - -// KillStatement represents a SQL KILL statement. -type KillStatement struct { - FB string - What Exprs -} - -// -------------------------------------------------- -// Normal -// -------------------------------------------------- - -// ReturnStatement represents a SQL RETURN statement. -type ReturnStatement struct { - RW bool - What Exprs -} - -// IfelseStatement represents a SQL IFELSE statement. -type IfelseStatement struct { - RW bool - Cond Exprs - Then Exprs - Else Expr -} - -// SelectStatement represents a SQL SELECT statement. -type SelectStatement struct { - RW bool - Expr Fields - What Exprs - Cond Expr - Split Idents - Group Groups - Order Orders - Limit Expr - Start Expr - Fetch Fetchs - Version Expr - Timeout time.Duration -} - -// CreateStatement represents a SQL CREATE statement. -type CreateStatement struct { - What Exprs - Data Expr - Echo Token - Timeout time.Duration -} - -// UpdateStatement represents a SQL UPDATE statement. -type UpdateStatement struct { - What Exprs - Data Expr - Cond Expr - Echo Token - Timeout time.Duration -} - -// DeleteStatement represents a SQL DELETE statement. -type DeleteStatement struct { - What Exprs - Cond Expr - Echo Token - Timeout time.Duration -} - -// RelateStatement represents a SQL RELATE statement. -type RelateStatement struct { - Type Expr - From Exprs - With Exprs - Data Expr - Uniq bool - Echo Token - Timeout time.Duration -} - -// InsertStatement represents a SQL INSERT statement. -type InsertStatement struct { - Data Expr - Into *Table - Echo Token - Timeout time.Duration -} - -// UpsertStatement represents a SQL UPSERT statement. -type UpsertStatement struct { - Data Expr - Into *Table - Echo Token - Timeout time.Duration -} - -// -------------------------------------------------- -// Namespace -// -------------------------------------------------- - -type DefineNamespaceStatement struct { - Name *Ident -} - -type RemoveNamespaceStatement struct { - Name *Ident -} - -// -------------------------------------------------- -// Database -// -------------------------------------------------- - -type DefineDatabaseStatement struct { - Name *Ident -} - -type RemoveDatabaseStatement struct { - Name *Ident -} - -// -------------------------------------------------- -// Login -// -------------------------------------------------- - -// DefineLoginStatement represents an SQL DEFINE LOGIN statement. -type DefineLoginStatement struct { - Kind Token - User *Ident - Pass []byte - Hash []byte - Code []byte -} - -// RemoveLoginStatement represents an SQL REMOVE LOGIN statement. -type RemoveLoginStatement struct { - Kind Token - User *Ident -} - -// -------------------------------------------------- -// Token -// -------------------------------------------------- - -// DefineTokenStatement represents an SQL DEFINE TOKEN statement. -type DefineTokenStatement struct { - Kind Token - Name *Ident - What *Ident - Type string - Code []byte -} - -// RemoveTokenStatement represents an SQL REMOVE TOKEN statement. -type RemoveTokenStatement struct { - Kind Token - Name *Ident - What *Ident -} - -// -------------------------------------------------- -// Scope -// -------------------------------------------------- - -// DefineScopeStatement represents an SQL DEFINE SCOPE statement. -type DefineScopeStatement struct { - Name *Ident - Time time.Duration - Code []byte - Signup Expr - Signin Expr - Connect Expr - OnSignup Expr - OnSignin Expr -} - -// RemoveScopeStatement represents an SQL REMOVE SCOPE statement. -type RemoveScopeStatement struct { - Name *Ident -} - -// -------------------------------------------------- -// Table -// -------------------------------------------------- - -// DefineTableStatement represents an SQL DEFINE TABLE statement. -type DefineTableStatement struct { - Name *Ident - What Tables - Full bool - Vers bool - Drop bool - Lock bool - Expr Fields - From Tables - Cond Expr - Group Groups - Perms Expr -} - -// RemoveTableStatement represents an SQL REMOVE TABLE statement. -type RemoveTableStatement struct { - What Tables -} - -// -------------------------------------------------- -// Event -// -------------------------------------------------- - -// DefineEventStatement represents an SQL DEFINE EVENT statement. -type DefineEventStatement struct { - Name *Ident - What Tables - When Expr - Then Expr -} - -// RemoveEventStatement represents an SQL REMOVE EVENT statement. -type RemoveEventStatement struct { - Name *Ident - What Tables -} - -// -------------------------------------------------- -// Field -// -------------------------------------------------- - -// DefineFieldStatement represents an SQL DEFINE FIELD statement. -type DefineFieldStatement struct { - Name *Ident - What Tables - Perms Expr - Type string - Kind string - Value Expr - Assert Expr - Priority float64 -} - -// RemoveFieldStatement represents an SQL REMOVE FIELD statement. -type RemoveFieldStatement struct { - Name *Ident - What Tables -} - -// -------------------------------------------------- -// Index -// -------------------------------------------------- - -// DefineIndexStatement represents an SQL DEFINE INDEX statement. -type DefineIndexStatement struct { - Name *Ident - What Tables - Cols Idents - Uniq bool -} - -// RemoveIndexStatement represents an SQL REMOVE INDEX statement. -type RemoveIndexStatement struct { - Name *Ident - What Tables -} - -// -------------------------------------------------- -// Literals -// -------------------------------------------------- - -// Expr represents a sql expression. -type Expr interface{} - -// Exprs represents multiple sql expressions. -type Exprs []Expr - -// All represents a * expression. -type All struct{} - -// Any represents a ? expression. -type Any struct{} - -// Null represents an expression which is null. -type Null struct{} - -// Void represents an expression which is not set. -type Void struct{} - -// Empty represents an expression which is null or "". -type Empty struct{} - -// Field represents a SELECT AS clause. -type Field struct { - Expr Expr - Field string - Alias string -} - -// Fields represents multiple SELECT AS clauses. -type Fields []*Field - -// Group represents a GROUP BY clause. -type Group struct { - Expr Expr -} - -// Groups represents multiple GROUP BY clauses. -type Groups []*Group - -// Order represents a ORDER BY clause. -type Order struct { - Expr Expr - Dir bool - Tag language.Tag -} - -// Orders represents multiple ORDER BY clauses. -type Orders []*Order - -// Fetch represents a FETCH AS clause. -type Fetch struct { - Expr Expr -} - -// Fetchs represents multiple FETCH AS clauses. -type Fetchs []*Fetch - -// -------------------------------------------------- -// Expressions -// -------------------------------------------------- - -// SubExpression represents a subquery. -type SubExpression struct { - Expr Expr -} - -// MultExpression represents multiple queries. -type MultExpression struct { - Expr []Expr -} - -// FuncExpression represents a function call. -type FuncExpression struct { - Name string - Args Exprs - Aggr bool -} - -// ItemExpression represents a part of a SET expression. -type ItemExpression struct { - LHS Expr - Op Token - RHS Expr -} - -// BinaryExpression represents a WHERE expression. -type BinaryExpression struct { - LHS Expr - Op Token - RHS Expr -} - -// PathExpression represents a path expression. -type PathExpression struct { - Expr Exprs -} - -// PartExpression represents a path part expression. -type PartExpression struct { - Part Expr -} - -// JoinExpression represents a path join expression. -type JoinExpression struct { - Join Token -} - -// SubpExpression represents a sub path expression. -type SubpExpression struct { - What Exprs - Name *Ident - Cond Expr -} - -// PermExpression represents a permissions expression. -type PermExpression struct { - Select Expr - Create Expr - Update Expr - Delete Expr -} - -// DataExpression represents a SET expression. -type DataExpression struct { - Data []*ItemExpression -} - -// DiffExpression represents a JSON to DIFF -type DiffExpression struct { - Data Expr -} - -// MergeExpression represents JSON to MERGE -type MergeExpression struct { - Data Expr -} - -// ContentExpression represents JSON to REPLACE -type ContentExpression struct { - Data Expr -} - -// -------------------------------------------------- -// Param -// -------------------------------------------------- - -// Params represents multiple Param clauses. -type Params []*Param - -// Param comment -type Param struct { - VA string -} - -func NewParam(VA string) *Param { - return &Param{VA} -} - -// -------------------------------------------------- -// Ident -// -------------------------------------------------- - -// Idents represents multiple Ident clauses. -type Idents []*Ident - -// Ident comment -type Ident struct { - VA string -} - -func NewIdent(VA string) *Ident { - return &Ident{VA} -} - -// -------------------------------------------------- -// Value -// -------------------------------------------------- - -// Values represents multiple Value clauses. -type Values []*Value - -// Value comment -type Value struct { - VA string -} - -func NewValue(VA string) *Value { - return &Value{VA} -} - -// -------------------------------------------------- -// Regex -// -------------------------------------------------- - -// Regexs represents multiple Regex clauses. -type Regexs []*Regex - -// Regex comment -type Regex struct { - VA string -} - -func NewRegex(VA string) *Regex { - return &Regex{VA} -} - -// -------------------------------------------------- -// Table -// -------------------------------------------------- - -// Tables represents multiple Table clauses. -type Tables []*Table - -// Table comment -type Table struct { - TB string -} - -func NewTable(TB string) *Table { - return &Table{TB} -} - -// -------------------------------------------------- -// Batch -// -------------------------------------------------- - -// Batchs represents multiple Batch clauses. -type Batchs []*Batch - -// Batch comment -type Batch struct { - TB string - BA []*Thing -} - -func NewBatch(TB string, BA []interface{}) *Batch { - var b = &Batch{TB: TB} - for _, ID := range BA { - b.BA = append(b.BA, NewThing(TB, ID)) - } - return b -} - -// -------------------------------------------------- -// Model -// -------------------------------------------------- - -// Models represents multiple Model clauses. -type Models []*Model - -// Model comment -type Model struct { - TB string - MIN float64 - INC float64 - MAX float64 -} - -func NewModel(TB string, MIN, INC, MAX float64) *Model { - return &Model{TB: TB, MIN: MIN, INC: INC, MAX: MAX} -} - -// -------------------------------------------------- -// Thing -// -------------------------------------------------- - -// Things represents multiple Thing clauses. -type Things []*Thing - -// Thing comment -type Thing struct { - TB string - ID interface{} -} - -func ParseThing(val string) *Thing { - r := strings.NewReader(val) - s := newScanner(r) - if t, _, v := s.scanIdiom(); t == THING { - return v.(*Thing) - } - return nil -} - -func NewThing(TB string, ID interface{}) *Thing { - switch val := ID.(type) { - default: - return &Thing{TB: TB, ID: ID} - case int: - return &Thing{TB: TB, ID: float64(val)} - case int64: - return &Thing{TB: TB, ID: float64(val)} - case string: - val = strings.Replace(val, TB+":", "", -1) - if cnv, err := strconv.ParseFloat(val, 64); err == nil { - return &Thing{TB: TB, ID: cnv} - } else if cnv, err := strconv.ParseBool(val); err == nil { - return &Thing{TB: TB, ID: cnv} - } else if cnv, err := time.Parse(RFCDate, val); err == nil { - return &Thing{TB: TB, ID: cnv.UTC()} - } else if cnv, err := time.Parse(RFCTime, val); err == nil { - return &Thing{TB: TB, ID: cnv.UTC()} - } - return &Thing{TB: TB, ID: val} - } -} - -// -------------------------------------------------- -// Point -// -------------------------------------------------- - -// Points represents multiple Point clauses. -type Points []*Point - -// Point comment -type Point struct { - LO float64 - LA float64 -} - -func NewPoint(LO, LA float64) *Point { - return &Point{LA: LA, LO: LO} -} - -// -------------------------------------------------- -// Circle -// -------------------------------------------------- - -// Circles represents multiple Circle clauses. -type Circles []*Circle - -// Circle comment -type Circle struct { - CE *Point - RA float64 -} - -func NewCircle(CE *Point, RA float64) *Circle { - return &Circle{CE: CE, RA: RA} -} - -// -------------------------------------------------- -// Polygon -// -------------------------------------------------- - -// Polygons represents multiple Polygon clauses. -type Polygons []*Polygon - -// Polygon comment -type Polygon struct { - PS []*Point -} - -func NewPolygon(PS ...*Point) *Polygon { - return &Polygon{PS: PS} -} diff --git a/sql/check.go b/sql/check.go deleted file mode 100644 index c76483c7..00000000 --- a/sql/check.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func checkExpression(allowed map[string]bool, expr Fields, grps Groups) error { - - if len(grps) > 0 { - - skip: - for _, e := range expr { - - for _, g := range grps { - - // If the expression in the SELECT - // clause is a field, then check to - // see if it exists in the GROUP BY. - - if i, ok := g.Expr.(*Ident); ok { - if e.Field == i.VA { - continue skip - } - } - - // Otherwise if the expression in - // the SELECT clause is a function - // then check to see if it is an - // aggregate function. - - if f, ok := e.Expr.(*FuncExpression); ok { - if ok = allowed[f.Name]; ok { - continue skip - } - } - - } - - // If the expression in the SELECT - // clause isn't an aggregate function - // and isn't specified in the GROUP BY - // clause, then raise an error. - - return &GroupError{found: e.Field} - - } - - } - - return nil - -} diff --git a/sql/cork.go b/sql/cork.go deleted file mode 100644 index 04969e47..00000000 --- a/sql/cork.go +++ /dev/null @@ -1,1560 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "github.com/surrealdb/cork" - "github.com/surrealdb/surrealdb/util/pack" -) - -func decode(src []byte, dst interface{}) { - pack.Decode(src, dst) -} - -func encode(src interface{}) (dst []byte) { - return pack.Encode(src) -} - -// -------------------------------------------------- -// ALL -// -------------------------------------------------- - -func init() { - cork.Register(&All{}) -} - -func (this *All) ExtendCORK() byte { - return 0x01 -} - -func (this *All) MarshalCORK(w *cork.Writer) (err error) { - return -} - -func (this *All) UnmarshalCORK(r *cork.Reader) (err error) { - return -} - -// -------------------------------------------------- -// ANY -// -------------------------------------------------- - -func init() { - cork.Register(&Any{}) -} - -func (this *Any) ExtendCORK() byte { - return 0x02 -} - -func (this *Any) MarshalCORK(w *cork.Writer) (err error) { - return -} - -func (this *Any) UnmarshalCORK(r *cork.Reader) (err error) { - return -} - -// -------------------------------------------------- -// NULL -// -------------------------------------------------- - -func init() { - cork.Register(&Null{}) -} - -func (this *Null) ExtendCORK() byte { - return 0x03 -} - -func (this *Null) MarshalCORK(w *cork.Writer) (err error) { - return -} - -func (this *Null) UnmarshalCORK(r *cork.Reader) (err error) { - return -} - -// -------------------------------------------------- -// VOID -// -------------------------------------------------- - -func init() { - cork.Register(&Void{}) -} - -func (this *Void) ExtendCORK() byte { - return 0x04 -} - -func (this *Void) MarshalCORK(w *cork.Writer) (err error) { - return -} - -func (this *Void) UnmarshalCORK(r *cork.Reader) (err error) { - return -} - -// -------------------------------------------------- -// EMPTY -// -------------------------------------------------- - -func init() { - cork.Register(&Empty{}) -} - -func (this *Empty) ExtendCORK() byte { - return 0x05 -} - -func (this *Empty) MarshalCORK(w *cork.Writer) (err error) { - return -} - -func (this *Empty) UnmarshalCORK(r *cork.Reader) (err error) { - return -} - -// -------------------------------------------------- -// FIELD -// -------------------------------------------------- - -func init() { - cork.Register(&Field{}) -} - -func (this *Field) ExtendCORK() byte { - return 0x06 -} - -func (this *Field) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Expr) - w.EncodeString(this.Field) - w.EncodeString(this.Alias) - return -} - -func (this *Field) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - r.DecodeString(&this.Field) - r.DecodeString(&this.Alias) - return -} - -// -------------------------------------------------- -// GROUP -// -------------------------------------------------- - -func init() { - cork.Register(&Group{}) -} - -func (this *Group) ExtendCORK() byte { - return 0x07 -} - -func (this *Group) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Expr) - return -} - -func (this *Group) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - return -} - -// -------------------------------------------------- -// ORDER -// -------------------------------------------------- - -func init() { - cork.Register(&Order{}) -} - -func (this *Order) ExtendCORK() byte { - return 0x08 -} - -func (this *Order) MarshalCORK(w *cork.Writer) (dst []byte, err error) { - w.EncodeAny(this.Expr) - w.EncodeAny(this.Dir) - return -} - -func (this *Order) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - r.DecodeAny(&this.Dir) - return -} - -// -------------------------------------------------- -// FETCH -// -------------------------------------------------- - -func init() { - cork.Register(&Fetch{}) -} - -func (this *Fetch) ExtendCORK() byte { - return 0x09 -} - -func (this *Fetch) MarshalCORK(w *cork.Writer) (dst []byte, err error) { - w.EncodeAny(this.Expr) - return -} - -func (this *Fetch) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - return -} - -// -------------------------------------------------- -// Param -// -------------------------------------------------- - -func init() { - cork.Register(&Param{}) -} - -func (this *Param) ExtendCORK() byte { - return 0x10 -} - -func (this *Param) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.VA) - return -} - -func (this *Param) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.VA) - return -} - -// -------------------------------------------------- -// Ident -// -------------------------------------------------- - -func init() { - cork.Register(&Ident{}) -} - -func (this *Ident) ExtendCORK() byte { - return 0x11 -} - -func (this *Ident) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.VA) - return -} - -func (this *Ident) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.VA) - return -} - -// -------------------------------------------------- -// Value -// -------------------------------------------------- - -func init() { - cork.Register(&Value{}) -} - -func (this *Value) ExtendCORK() byte { - return 0x12 -} - -func (this *Value) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.VA) - return -} - -func (this *Value) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.VA) - return -} - -// -------------------------------------------------- -// Regex -// -------------------------------------------------- - -func init() { - cork.Register(&Regex{}) -} - -func (this *Regex) ExtendCORK() byte { - return 0x13 -} - -func (this *Regex) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.VA) - return -} - -func (this *Regex) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.VA) - return -} - -// -------------------------------------------------- -// Table -// -------------------------------------------------- - -func init() { - cork.Register(&Table{}) -} - -func (this *Table) ExtendCORK() byte { - return 0x14 -} - -func (this *Table) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.TB) - return -} - -func (this *Table) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.TB) - return -} - -// -------------------------------------------------- -// Batch -// -------------------------------------------------- - -func init() { - cork.Register(&Batch{}) -} - -func (this *Batch) ExtendCORK() byte { - return 0x15 -} - -func (this *Batch) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.BA) - return -} - -func (this *Batch) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.BA) - return -} - -// -------------------------------------------------- -// Model -// -------------------------------------------------- - -func init() { - cork.Register(&Model{}) -} - -func (this *Model) ExtendCORK() byte { - return 0x16 -} - -func (this *Model) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.TB) - w.EncodeFloat64(this.MIN) - w.EncodeFloat64(this.INC) - w.EncodeFloat64(this.MAX) - return -} - -func (this *Model) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.TB) - r.DecodeFloat64(&this.MIN) - r.DecodeFloat64(&this.INC) - r.DecodeFloat64(&this.MAX) - return -} - -// -------------------------------------------------- -// Thing -// -------------------------------------------------- - -func init() { - cork.Register(&Thing{}) -} - -func (this Thing) Bytes() []byte { - return []byte(this.String()) -} - -func (this *Thing) ExtendCORK() byte { - return 0x17 -} - -func (this *Thing) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.TB) - w.EncodeAny(this.ID) - return -} - -func (this *Thing) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.TB) - r.DecodeAny(&this.ID) - return -} - -func (this Thing) MarshalText() (data []byte, err error) { - return []byte(this.String()), err -} - -// -------------------------------------------------- -// Point -// -------------------------------------------------- - -func init() { - cork.Register(&Point{}) -} - -func (this *Point) ExtendCORK() byte { - return 0x18 -} - -func (this *Point) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeFloat64(this.LA) - w.EncodeFloat64(this.LO) - return -} - -func (this *Point) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeFloat64(&this.LA) - r.DecodeFloat64(&this.LO) - return -} - -func (this Point) MarshalText() (data []byte, err error) { - return []byte(this.String()), err -} - -func (this Point) MarshalJSON() (data []byte, err error) { - return []byte(this.JSON()), err -} - -// -------------------------------------------------- -// Circle -// -------------------------------------------------- - -func init() { - cork.Register(&Circle{}) -} - -func (this *Circle) ExtendCORK() byte { - return 0x19 -} - -func (this *Circle) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.CE) - w.EncodeFloat64(this.RA) - return -} - -func (this *Circle) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.CE) - r.DecodeFloat64(&this.RA) - return -} - -func (this Circle) MarshalText() (data []byte, err error) { - return []byte(this.String()), err -} - -func (this Circle) MarshalJSON() (data []byte, err error) { - return []byte(this.JSON()), err -} - -// -------------------------------------------------- -// Polygon -// -------------------------------------------------- - -func init() { - cork.Register(&Polygon{}) -} - -func (this *Polygon) ExtendCORK() byte { - return 0x20 -} - -func (this *Polygon) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.PS) - return -} - -func (this *Polygon) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.PS) - return -} - -func (this Polygon) MarshalText() (data []byte, err error) { - return []byte(this.String()), err -} - -func (this Polygon) MarshalJSON() (data []byte, err error) { - return []byte(this.JSON()), err -} - -// -------------------------------------------------- -// SubExpression -// -------------------------------------------------- - -func init() { - cork.Register(&SubExpression{}) -} - -func (this *SubExpression) ExtendCORK() byte { - return 0x21 -} - -func (this *SubExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Expr) - return -} - -func (this *SubExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - return -} - -// -------------------------------------------------- -// MultExpression -// -------------------------------------------------- - -func init() { - cork.Register(&MultExpression{}) -} - -func (this *MultExpression) ExtendCORK() byte { - return 0x22 -} - -func (this *MultExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Expr) - return -} - -func (this *MultExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - return -} - -// -------------------------------------------------- -// FuncExpression -// -------------------------------------------------- - -func init() { - cork.Register(&FuncExpression{}) -} - -func (this *FuncExpression) ExtendCORK() byte { - return 0x24 -} - -func (this *FuncExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.Name) - w.EncodeAny(this.Args) - w.EncodeBool(this.Aggr) - return -} - -func (this *FuncExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.Name) - r.DecodeAny(&this.Args) - r.DecodeBool(&this.Aggr) - return -} - -// -------------------------------------------------- -// ItemExpression -// -------------------------------------------------- - -func init() { - cork.Register(&ItemExpression{}) -} - -func (this *ItemExpression) ExtendCORK() byte { - return 0x25 -} - -func (this *ItemExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.LHS) - w.EncodeAny(this.Op) - w.EncodeAny(this.RHS) - return -} - -func (this *ItemExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.LHS) - r.DecodeAny(&this.Op) - r.DecodeAny(&this.RHS) - return -} - -// -------------------------------------------------- -// BinaryExpression -// -------------------------------------------------- - -func init() { - cork.Register(&BinaryExpression{}) -} - -func (this *BinaryExpression) ExtendCORK() byte { - return 0x26 -} - -func (this *BinaryExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.LHS) - w.EncodeAny(this.Op) - w.EncodeAny(this.RHS) - return -} - -func (this *BinaryExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.LHS) - r.DecodeAny(&this.Op) - r.DecodeAny(&this.RHS) - return -} - -// -------------------------------------------------- -// PathExpression -// -------------------------------------------------- - -func init() { - cork.Register(&PathExpression{}) -} - -func (this *PathExpression) ExtendCORK() byte { - return 0x27 -} - -func (this *PathExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Expr) - return -} - -func (this *PathExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - return -} - -// -------------------------------------------------- -// PartExpression -// -------------------------------------------------- - -func init() { - cork.Register(&PartExpression{}) -} - -func (this *PartExpression) ExtendCORK() byte { - return 0x28 -} - -func (this *PartExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Part) - return -} - -func (this *PartExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Part) - return -} - -// -------------------------------------------------- -// JoinExpression -// -------------------------------------------------- - -func init() { - cork.Register(&JoinExpression{}) -} - -func (this *JoinExpression) ExtendCORK() byte { - return 0x29 -} - -func (this *JoinExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Join) - return -} - -func (this *JoinExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Join) - return -} - -// -------------------------------------------------- -// SubpExpression -// -------------------------------------------------- - -func init() { - cork.Register(&SubpExpression{}) -} - -func (this *SubpExpression) ExtendCORK() byte { - return 0x30 -} - -func (this *SubpExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.What) - w.EncodeAny(this.Name) - w.EncodeAny(this.Cond) - return -} - -func (this *SubpExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.What) - r.DecodeAny(&this.Name) - r.DecodeAny(&this.Cond) - return -} - -// -------------------------------------------------- -// PermExpression -// -------------------------------------------------- - -func init() { - cork.Register(&PermExpression{}) -} - -func (this *PermExpression) ExtendCORK() byte { - return 0x31 -} - -func (this *PermExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Select) - w.EncodeAny(this.Create) - w.EncodeAny(this.Update) - w.EncodeAny(this.Delete) - return -} - -func (this *PermExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Select) - r.DecodeAny(&this.Create) - r.DecodeAny(&this.Update) - r.DecodeAny(&this.Delete) - return -} - -// -------------------------------------------------- -// DataExpression -// -------------------------------------------------- - -func init() { - cork.Register(&DataExpression{}) -} - -func (this *DataExpression) ExtendCORK() byte { - return 0x32 -} - -func (this *DataExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Data) - return -} - -func (this *DataExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Data) - return -} - -// -------------------------------------------------- -// DiffExpression -// -------------------------------------------------- - -func init() { - cork.Register(&DiffExpression{}) -} - -func (this *DiffExpression) ExtendCORK() byte { - return 0x33 -} - -func (this *DiffExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Data) - return -} - -func (this *DiffExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Data) - return -} - -// -------------------------------------------------- -// MergeExpression -// -------------------------------------------------- - -func init() { - cork.Register(&MergeExpression{}) -} - -func (this *MergeExpression) ExtendCORK() byte { - return 0x34 -} - -func (this *MergeExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Data) - return -} - -func (this *MergeExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Data) - return -} - -// -------------------------------------------------- -// ContentExpression -// -------------------------------------------------- - -func init() { - cork.Register(&ContentExpression{}) -} - -func (this *ContentExpression) ExtendCORK() byte { - return 0x35 -} - -func (this *ContentExpression) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Data) - return -} - -func (this *ContentExpression) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Data) - return -} - -// -------------------------------------------------- -// RunStatement -// -------------------------------------------------- - -func init() { - cork.Register(&RunStatement{}) -} - -func (this *RunStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *RunStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *RunStatement) ExtendCORK() byte { - return 0x36 -} - -func (this *RunStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Expr) - return -} - -func (this *RunStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Expr) - return -} - -// -------------------------------------------------- -// LiveStatement -// -------------------------------------------------- - -func init() { - cork.Register(&LiveStatement{}) -} - -func (this *LiveStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *LiveStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *LiveStatement) ExtendCORK() byte { - return 0x37 -} - -func (this *LiveStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeString(this.FB) - w.EncodeString(this.ID) - w.EncodeBool(this.Diff) - w.EncodeAny(this.Expr) - w.EncodeAny(this.What) - w.EncodeAny(this.Cond) - w.EncodeAny(this.Fetch) - return -} - -func (this *LiveStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeString(&this.FB) - r.DecodeString(&this.ID) - r.DecodeBool(&this.Diff) - r.DecodeAny(&this.Expr) - r.DecodeAny(&this.What) - r.DecodeAny(&this.Cond) - r.DecodeAny(&this.Fetch) - return -} - -// -------------------------------------------------- -// IfelseStatement -// -------------------------------------------------- - -func init() { - cork.Register(&IfelseStatement{}) -} - -func (this *IfelseStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *IfelseStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *IfelseStatement) ExtendCORK() byte { - return 0x38 -} - -func (this *IfelseStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Cond) - w.EncodeAny(this.Then) - w.EncodeAny(this.Else) - return -} - -func (this *IfelseStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Cond) - r.DecodeAny(&this.Then) - r.DecodeAny(&this.Else) - return -} - -// -------------------------------------------------- -// SelectStatement -// -------------------------------------------------- - -func init() { - cork.Register(&SelectStatement{}) -} - -func (this *SelectStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *SelectStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *SelectStatement) ExtendCORK() byte { - return 0x39 -} - -func (this *SelectStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeBool(this.RW) - w.EncodeAny(this.Expr) - w.EncodeAny(this.What) - w.EncodeAny(this.Cond) - w.EncodeAny(this.Group) - w.EncodeAny(this.Order) - w.EncodeAny(this.Limit) - w.EncodeAny(this.Start) - w.EncodeAny(this.Fetch) - w.EncodeAny(this.Version) - w.EncodeAny(this.Timeout) - return -} - -func (this *SelectStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeBool(&this.RW) - r.DecodeAny(&this.Expr) - r.DecodeAny(&this.What) - r.DecodeAny(&this.Cond) - r.DecodeAny(&this.Group) - r.DecodeAny(&this.Order) - r.DecodeAny(&this.Limit) - r.DecodeAny(&this.Start) - r.DecodeAny(&this.Fetch) - r.DecodeAny(&this.Version) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// CreateStatement -// -------------------------------------------------- - -func init() { - cork.Register(&CreateStatement{}) -} - -func (this *CreateStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *CreateStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *CreateStatement) ExtendCORK() byte { - return 0x40 -} - -func (this *CreateStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.What) - w.EncodeAny(this.Data) - w.EncodeAny(this.Echo) - w.EncodeAny(this.Timeout) - return -} - -func (this *CreateStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.What) - r.DecodeAny(&this.Data) - r.DecodeAny(&this.Echo) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// UpdateStatement -// -------------------------------------------------- - -func init() { - cork.Register(&UpdateStatement{}) -} - -func (this *UpdateStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *UpdateStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *UpdateStatement) ExtendCORK() byte { - return 0x41 -} - -func (this *UpdateStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.What) - w.EncodeAny(this.Data) - w.EncodeAny(this.Cond) - w.EncodeAny(this.Echo) - w.EncodeAny(this.Timeout) - return -} - -func (this *UpdateStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.What) - r.DecodeAny(&this.Data) - r.DecodeAny(&this.Cond) - r.DecodeAny(&this.Echo) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// DeleteStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DeleteStatement{}) -} - -func (this *DeleteStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DeleteStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DeleteStatement) ExtendCORK() byte { - return 0x42 -} - -func (this *DeleteStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.What) - w.EncodeAny(this.Cond) - w.EncodeAny(this.Echo) - w.EncodeAny(this.Timeout) - return -} - -func (this *DeleteStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.What) - r.DecodeAny(&this.Cond) - r.DecodeAny(&this.Echo) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// RelateStatement -// -------------------------------------------------- - -func init() { - cork.Register(&RelateStatement{}) -} - -func (this *RelateStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *RelateStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *RelateStatement) ExtendCORK() byte { - return 0x43 -} - -func (this *RelateStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Type) - w.EncodeAny(this.From) - w.EncodeAny(this.With) - w.EncodeAny(this.Data) - w.EncodeBool(this.Uniq) - w.EncodeAny(this.Echo) - w.EncodeAny(this.Timeout) - return -} - -func (this *RelateStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Type) - r.DecodeAny(&this.From) - r.DecodeAny(&this.With) - r.DecodeAny(&this.Data) - r.DecodeBool(&this.Uniq) - r.DecodeAny(&this.Echo) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// InsertStatement -// -------------------------------------------------- - -func init() { - cork.Register(&InsertStatement{}) -} - -func (this *InsertStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *InsertStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *InsertStatement) ExtendCORK() byte { - return 0x44 -} - -func (this *InsertStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Data) - w.EncodeAny(this.Into) - w.EncodeAny(this.Echo) - w.EncodeAny(this.Timeout) - return -} - -func (this *InsertStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Data) - r.DecodeAny(&this.Into) - r.DecodeAny(&this.Echo) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// UpsertStatement -// -------------------------------------------------- - -func init() { - cork.Register(&UpsertStatement{}) -} - -func (this *UpsertStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *UpsertStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *UpsertStatement) ExtendCORK() byte { - return 0x45 -} - -func (this *UpsertStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Data) - w.EncodeAny(this.Into) - w.EncodeAny(this.Echo) - w.EncodeAny(this.Timeout) - return -} - -func (this *UpsertStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Data) - r.DecodeAny(&this.Into) - r.DecodeAny(&this.Echo) - r.DecodeAny(&this.Timeout) - return -} - -// -------------------------------------------------- -// DefineNamespaceStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineNamespaceStatement{}) -} - -func (this *DefineNamespaceStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineNamespaceStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineNamespaceStatement) ExtendCORK() byte { - return 0x46 -} - -func (this *DefineNamespaceStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - return -} - -func (this *DefineNamespaceStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - return -} - -// -------------------------------------------------- -// DefineDatabaseStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineDatabaseStatement{}) -} - -func (this *DefineDatabaseStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineDatabaseStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineDatabaseStatement) ExtendCORK() byte { - return 0x47 -} - -func (this *DefineDatabaseStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - return -} - -func (this *DefineDatabaseStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - return -} - -// -------------------------------------------------- -// DefineLoginStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineLoginStatement{}) -} - -func (this *DefineLoginStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineLoginStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineLoginStatement) ExtendCORK() byte { - return 0x48 -} - -func (this *DefineLoginStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Kind) - w.EncodeAny(this.User) - w.EncodeBytes(this.Pass) - w.EncodeBytes(this.Code) - return -} - -func (this *DefineLoginStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Kind) - r.DecodeAny(&this.User) - r.DecodeBytes(&this.Pass) - r.DecodeBytes(&this.Code) - return -} - -// -------------------------------------------------- -// DefineTokenStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineTokenStatement{}) -} - -func (this *DefineTokenStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineTokenStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineTokenStatement) ExtendCORK() byte { - return 0x49 -} - -func (this *DefineTokenStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Kind) - w.EncodeAny(this.Name) - w.EncodeAny(this.What) - w.EncodeAny(this.Type) - w.EncodeBytes(this.Code) - return -} - -func (this *DefineTokenStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Kind) - r.DecodeAny(&this.Name) - r.DecodeAny(&this.What) - r.DecodeAny(&this.Type) - r.DecodeBytes(&this.Code) - return -} - -// -------------------------------------------------- -// DefineScopeStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineScopeStatement{}) -} - -func (this *DefineScopeStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineScopeStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineScopeStatement) ExtendCORK() byte { - return 0x50 -} - -func (this *DefineScopeStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - w.EncodeAny(this.Time) - w.EncodeBytes(this.Code) - w.EncodeAny(this.Signup) - w.EncodeAny(this.Signin) - w.EncodeAny(this.Connect) - w.EncodeAny(this.OnSignup) - w.EncodeAny(this.OnSignin) - return -} - -func (this *DefineScopeStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - r.DecodeAny(&this.Time) - r.DecodeBytes(&this.Code) - r.DecodeAny(&this.Signup) - r.DecodeAny(&this.Signin) - r.DecodeAny(&this.Connect) - r.DecodeAny(&this.OnSignup) - r.DecodeAny(&this.OnSignin) - return -} - -// -------------------------------------------------- -// DefineTableStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineTableStatement{}) -} - -func (this *DefineTableStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineTableStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineTableStatement) ExtendCORK() byte { - return 0x51 -} - -func (this *DefineTableStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - w.EncodeBool(this.Full) - w.EncodeBool(this.Vers) - w.EncodeBool(this.Drop) - w.EncodeBool(this.Lock) - w.EncodeAny(this.Expr) - w.EncodeAny(this.From) - w.EncodeAny(this.Cond) - w.EncodeAny(this.Group) - w.EncodeAny(this.Perms) - return -} - -func (this *DefineTableStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - r.DecodeBool(&this.Full) - r.DecodeBool(&this.Vers) - r.DecodeBool(&this.Drop) - r.DecodeBool(&this.Lock) - r.DecodeAny(&this.Expr) - r.DecodeAny(&this.From) - r.DecodeAny(&this.Cond) - r.DecodeAny(&this.Group) - r.DecodeAny(&this.Perms) - return -} - -// -------------------------------------------------- -// DefineEventStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineEventStatement{}) -} - -func (this *DefineEventStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineEventStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineEventStatement) ExtendCORK() byte { - return 0x52 -} - -func (this *DefineEventStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - w.EncodeAny(this.What) - w.EncodeAny(this.When) - w.EncodeAny(this.Then) - return -} - -func (this *DefineEventStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - r.DecodeAny(&this.What) - r.DecodeAny(&this.When) - r.DecodeAny(&this.Then) - return -} - -// -------------------------------------------------- -// DefineFieldStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineFieldStatement{}) -} - -func (this *DefineFieldStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineFieldStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineFieldStatement) ExtendCORK() byte { - return 0x53 -} - -func (this *DefineFieldStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - w.EncodeAny(this.What) - w.EncodeString(this.Type) - w.EncodeString(this.Kind) - w.EncodeAny(this.Perms) - w.EncodeAny(this.Value) - w.EncodeAny(this.Assert) - w.EncodeAny(this.Priority) - return -} - -func (this *DefineFieldStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - r.DecodeAny(&this.What) - r.DecodeString(&this.Type) - r.DecodeString(&this.Kind) - r.DecodeAny(&this.Perms) - r.DecodeAny(&this.Value) - r.DecodeAny(&this.Assert) - r.DecodeAny(&this.Priority) - return -} - -// -------------------------------------------------- -// DefineIndexStatement -// -------------------------------------------------- - -func init() { - cork.Register(&DefineIndexStatement{}) -} - -func (this *DefineIndexStatement) Decode(src []byte) { - pack.Decode(src, this) -} - -func (this *DefineIndexStatement) Encode() (dst []byte) { - return pack.Encode(this) -} - -func (this *DefineIndexStatement) ExtendCORK() byte { - return 0x54 -} - -func (this *DefineIndexStatement) MarshalCORK(w *cork.Writer) (err error) { - w.EncodeAny(this.Name) - w.EncodeAny(this.What) - w.EncodeAny(this.Cols) - w.EncodeBool(this.Uniq) - return -} - -func (this *DefineIndexStatement) UnmarshalCORK(r *cork.Reader) (err error) { - r.DecodeAny(&this.Name) - r.DecodeAny(&this.What) - r.DecodeAny(&this.Cols) - r.DecodeBool(&this.Uniq) - return -} diff --git a/sql/create.go b/sql/create.go deleted file mode 100644 index 96eef4f3..00000000 --- a/sql/create.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseCreateStatement() (stmt *CreateStatement, err error) { - - stmt = &CreateStatement{} - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - if stmt.Data, err = p.parseData(); err != nil { - return nil, err - } - - if stmt.Echo, err = p.parseEcho(AFTER); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/data.go b/sql/data.go deleted file mode 100644 index 783e999c..00000000 --- a/sql/data.go +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseData() (exp Expr, err error) { - - if tok, _, exi := p.mightBe(SET, DIFF, MERGE, CONTENT); exi { - - if is(tok, SET) { - if exp, err = p.parseSet(); err != nil { - return nil, err - } - } - - if is(tok, DIFF) { - if exp, err = p.parseDiff(); err != nil { - return nil, err - } - } - - if is(tok, MERGE) { - if exp, err = p.parseMerge(); err != nil { - return nil, err - } - } - - if is(tok, CONTENT) { - if exp, err = p.parseContent(); err != nil { - return nil, err - } - } - - } - - return - -} - -func (p *parser) parseSet() (mul Expr, err error) { - - out := &DataExpression{} - - for { - - var tok Token - var lit string - - one := &ItemExpression{} - - // The first part of a SET expression must - // always be an identifier, specifying a - // record field to set. - - tok, lit, err = p.shouldBe(IDENT, EXPR) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"field name"}} - } - - one.LHS, err = p.declare(tok, lit) - if err != nil { - return nil, err - } - - // The next query part must be a =, +=, or - // -= operator, as this is a SET expression - // and not a binary expression. - - one.Op, lit, err = p.shouldBe(EQ, INC, DEC) - if err != nil { - return nil, err - } - - // The next query part can be any expression - // including a parenthesised expression or a - // binary expression so handle accordingly. - - one.RHS, err = p.parseExpr() - if err != nil { - return nil, err - } - - // Append the single SET data expression to - // the array of data expressions. - - out.Data = append(out.Data, one) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return out, err - -} - -func (p *parser) parseDiff() (exp *DiffExpression, err error) { - - exp = &DiffExpression{} - - tok, lit, err := p.shouldBe(ARRAY, PARAM) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"json"}} - } - - exp.Data, err = p.declare(tok, lit) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"json"}} - } - - return - -} - -func (p *parser) parseMerge() (exp *MergeExpression, err error) { - - exp = &MergeExpression{} - - tok, lit, err := p.shouldBe(JSON, PARAM) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"json"}} - } - - exp.Data, err = p.declare(tok, lit) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"json"}} - } - - return - -} - -func (p *parser) parseContent() (exp *ContentExpression, err error) { - - exp = &ContentExpression{} - - tok, lit, err := p.shouldBe(JSON, PARAM) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"json"}} - } - - exp.Data, err = p.declare(tok, lit) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"json"}} - } - - return - -} diff --git a/sql/database.go b/sql/database.go deleted file mode 100644 index b5621b03..00000000 --- a/sql/database.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineDatabaseStatement() (stmt *DefineDatabaseStatement, err error) { - - stmt = &DefineDatabaseStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - return - -} - -func (p *parser) parseRemoveDatabaseStatement() (stmt *RemoveDatabaseStatement, err error) { - - stmt = &RemoveDatabaseStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/define.go b/sql/define.go deleted file mode 100644 index b24117e7..00000000 --- a/sql/define.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineStatement() (Statement, error) { - - // Inspect the next token. - tok, _, err := p.shouldBe(NAMESPACE, DATABASE, LOGIN, TOKEN, SCOPE, TABLE, EVENT, FIELD, INDEX) - - switch tok { - case NAMESPACE: - return p.parseDefineNamespaceStatement() - case DATABASE: - return p.parseDefineDatabaseStatement() - case LOGIN: - return p.parseDefineLoginStatement() - case TOKEN: - return p.parseDefineTokenStatement() - case SCOPE: - return p.parseDefineScopeStatement() - case TABLE: - return p.parseDefineTableStatement() - case EVENT: - return p.parseDefineEventStatement() - case FIELD: - return p.parseDefineFieldStatement() - case INDEX: - return p.parseDefineIndexStatement() - default: - return nil, err - } - -} diff --git a/sql/delete.go b/sql/delete.go deleted file mode 100644 index 4fa7fee7..00000000 --- a/sql/delete.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDeleteStatement() (stmt *DeleteStatement, err error) { - - stmt = &DeleteStatement{} - - _, _, _ = p.mightBe(FROM) - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - if stmt.Cond, err = p.parseCond(); err != nil { - return nil, err - } - - if stmt.Echo, err = p.parseEcho(NONE); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/echo.go b/sql/echo.go deleted file mode 100644 index 75084e37..00000000 --- a/sql/echo.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseEcho(fallback Token) (exp Token, err error) { - - exp = fallback - - // The next token that we expect to see is a - // RETURN token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(RETURN); exi { - - exp, _, err = p.shouldBe(NONE, BEFORE, AFTER) - if err != nil { - return 0, err - } - - } - - return - -} diff --git a/sql/error.go b/sql/error.go deleted file mode 100644 index 3a0b3228..00000000 --- a/sql/error.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "fmt" - "strings" -) - -// EmptyError represents an error that occurred during parsing. -type EmptyError struct{} - -// Error returns the string representation of the error. -func (e *EmptyError) Error() string { - return fmt.Sprint("Your SQL query is empty") -} - -// GroupError occurs when a 'group' expression is invalid. -type GroupError struct { - found interface{} -} - -// Error returns the string representation of the error. -func (e *GroupError) Error() string { - return fmt.Sprintf("Found '%v' but field is not an aggregate function, and is not present in GROUP expression", e.found) -} - -// ParseError represents an error that occurred during parsing. -type ParseError struct { - Found string - Expected []string -} - -// Error returns the string representation of the error. -func (e *ParseError) Error() string { - if len(e.Found) > 1000 { - return fmt.Sprintf("Found `%s...` but expected `%s`", e.Found[:1000], strings.Join(e.Expected, ", ")) - } - return fmt.Sprintf("Found `%s` but expected `%s`", e.Found, strings.Join(e.Expected, ", ")) -} diff --git a/sql/event.go b/sql/event.go deleted file mode 100644 index aefa4a43..00000000 --- a/sql/event.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineEventStatement() (stmt *DefineEventStatement, err error) { - - stmt = &DefineEventStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(WHEN); err != nil { - return nil, err - } - - if stmt.When, err = p.parseExpr(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(THEN); err != nil { - return nil, err - } - - if stmt.Then, err = p.parseMult(); err != nil { - return nil, err - } - - return - -} - -func (p *parser) parseRemoveEventStatement() (stmt *RemoveEventStatement, err error) { - - stmt = &RemoveEventStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/exprs.go b/sql/exprs.go deleted file mode 100644 index 12029f31..00000000 --- a/sql/exprs.go +++ /dev/null @@ -1,973 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "fmt" - "sort" - "time" - - "golang.org/x/text/language" -) - -func (p *parser) parseWhat() (mul []Expr, err error) { - - for { - - exp, err := p.parsePart() - if err != nil { - return nil, err - } - - mul = append(mul, exp) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseIdent() (*Ident, error) { - - _, lit, err := p.shouldBe(IDENT) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"name"}} - } - - val, err := p.declare(IDENT, lit) - - return val.(*Ident), err - -} - -func (p *parser) parseIdents() (mul Idents, err error) { - - for { - - one, err := p.parseIdent() - if err != nil { - return nil, err - } - - mul = append(mul, one) - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseTable() (*Table, error) { - - _, lit, err := p.shouldBe(IDENT) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"table"}} - } - - val, err := p.declare(TABLE, lit) - - return val.(*Table), err - -} - -func (p *parser) parseTables() (mul Tables, err error) { - - for { - - one, err := p.parseTable() - if err != nil { - return nil, err - } - - mul = append(mul, one) - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseIdiom() (*Ident, error) { - - _, lit, err := p.shouldBe(IDENT, EXPR) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"name, or expression"}} - } - - val, err := p.declare(IDENT, lit) - - return val.(*Ident), err - -} - -func (p *parser) parseIdioms() (mul Idents, err error) { - - for { - - one, err := p.parseIdiom() - if err != nil { - return nil, err - } - - mul = append(mul, one) - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseParam() (*Ident, error) { - - _, lit, err := p.shouldBe(IDENT, PARAM) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"name"}} - } - - val, err := p.declare(IDENT, lit) - - return val.(*Ident), err - -} - -// -------------------------------------------------- -// -// -------------------------------------------------- - -func (p *parser) parseCond() (exp Expr, err error) { - - // The next token that we expect to see is a - // WHERE token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(WHERE); !exi { - return nil, nil - } - - return p.parseExpr() - -} - -// -------------------------------------------------- -// -// -------------------------------------------------- - -func (p *parser) parseBool() (bool, error) { - - tok, lit, err := p.shouldBe(TRUE, FALSE) - if err != nil { - return false, &ParseError{Found: lit, Expected: []string{"true", "false"}} - } - - val, err := p.declare(tok, lit) - - return val.(bool), err - -} - -func (p *parser) parseBinary() ([]byte, error) { - - _, lit, err := p.shouldBe(STRING, REGION) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"string"}} - } - - return []byte(lit), err - -} - -func (p *parser) parseTimeout() (time.Duration, error) { - - if _, _, exi := p.mightBe(TIMEOUT); !exi { - return 0, nil - } - - return p.parseDuration() - -} - -func (p *parser) parseDuration() (time.Duration, error) { - - tok, lit, err := p.shouldBe(DURATION) - if err != nil { - return 0, &ParseError{Found: lit, Expected: []string{"duration"}} - } - - val, err := p.declare(tok, lit) - - return val.(time.Duration), err - -} - -func (p *parser) parsePriority() (float64, error) { - - tok, lit, err := p.shouldBe(NUMBER) - if err != nil { - return 0, &ParseError{Found: lit, Expected: []string{"number"}} - } - - val, err := p.declare(tok, lit) - - return val.(float64), err - -} - -func (p *parser) parseParallel() (bool, error) { - - if _, _, exi := p.mightBe(PARALLEL); !exi { - return true, nil - } - - tok, lit, err := p.shouldBe(TRUE, FALSE) - if err != nil { - return true, &ParseError{Found: lit, Expected: []string{"true", "false"}} - } - - val, err := p.declare(tok, lit) - - return val.(bool), err - -} - -func (p *parser) parseType() (t, k string, err error) { - - _, t, err = p.shouldBe(IDENT, STRING, PASSWORD) - if err != nil { - err = &ParseError{Found: t, Expected: allowedTypes} - return - } - - if !contains(t, allowedTypes) { - err = &ParseError{Found: t, Expected: allowedTypes} - return - } - - if t == "record" { - if _, _, exi := p.mightBe(LPAREN); exi { - if _, k, err = p.shouldBe(IDENT); err != nil { - return - } - if _, _, err = p.shouldBe(RPAREN); err != nil { - return - } - } - } - - return - -} - -func (p *parser) parseLanguage() (tag language.Tag, err error) { - - tag = language.English - - if _, lit, exi := p.mightBe(IDENT, STRING); exi { - - if tag, err = language.Parse(lit); err != nil { - return tag, &ParseError{Found: lit, Expected: []string{"BCP47 language"}} - } - - } - - if _, _, exi := p.mightBe(NUMERIC); exi { - tag, _ = tag.SetTypeForKey("kn", "true") - } - - return tag, nil - -} - -func (p *parser) parseAlgorithm() (string, error) { - - _, lit, err := p.shouldBe(IDENT, STRING) - if err != nil { - return string(""), &ParseError{Found: lit, Expected: allowedAlgorithms} - } - - switch lit { - case - "ES256", "ES384", "ES512", - "HS256", "HS384", "HS512", - "PS256", "PS384", "PS512", - "RS256", "RS384", "RS512": - default: - return string(""), &ParseError{Found: lit, Expected: allowedAlgorithms} - } - - return lit, err - -} - -func (p *parser) parseExpr() (exp Expr, err error) { - - // Create the root binary expression tree. - - root := &BinaryExpression{} - - // If the primary token is an in, out, or - // multi way path expression, then follow - // the path through to the end. - - if tok, _, exi := p.mightBe(OEDGE, IEDGE, BEDGE); exi { - - root.RHS, err = p.parsePath(tok) - if err != nil { - return nil, err - } - - } else { - - // Otherwise begin with parsing the first - // expression, as the root of the tree. - - root.RHS, err = p.parsePart() - if err != nil { - return nil, err - } - - // But if the subsequent token is an in, out, - // or multi way path expression, then follow - // the path through to the end. - - if tok, _, exi := p.mightBe(DOT, OEDGE, IEDGE, BEDGE); exi { - - root.RHS, err = p.parsePath(root.RHS, tok) - if err != nil { - return nil, err - } - - } - - } - - // Loop over the operations and expressions - // and build a binary expression tree based - // on the precedence of the operators. - - for { - - var rhs Expr - - // Get the next token from the scanner and - // the literal value that it is scanned as. - - tok, lit, _ := p.scan() - - switch tok { - - // If the token is an AND or OR expression - // then skip to the next expression without - // further checks. - - case AND, OR: - - // If the token is not an operator but can - // be converted into an operator based on - // logic, then convert it to an operator. - - case IN: - - tok = INS - if _, _, exi := p.mightBe(NOT); exi { - tok = NIS - } - - case CONTAINS: - - tok = SIN - if _, _, exi := p.mightBe(NOT); exi { - tok = SNI - } - - case IS: - - tok = EQ - if _, _, exi := p.mightBe(NOT); exi { - tok = NEQ - } - if _, _, exi := p.mightBe(IN); exi { - switch tok { - case EQ: - tok = INS - case NEQ: - tok = NIS - } - } - - // If the token is a keyword which is also - // actually an operator, then skip to the - // next expression without further checks. - - case CONTAINSALL, CONTAINSNONE, CONTAINSSOME: - - case ALLCONTAINEDIN, NONECONTAINEDIN, SOMECONTAINEDIN: - - // If the token is an int64 or a float64 then - // check to see whether the first rune is a - // + or a - and use it as a token instead. - - case NUMBER, DOUBLE: - - switch lit[0] { - case '-': - rhs, err = p.declare(tok, lit[1:]) - tok = SUB - case '+': - rhs, err = p.declare(tok, lit[1:]) - tok = ADD - default: - p.unscan() - return root.RHS, nil - } - - // Check to see if the token is an operator - // expression. If it is none of those then - // unscan and break out of the loop. - - default: - - if !tok.isOperator() { - p.unscan() - return root.RHS, nil - } - - } - - // If the token was not an int64 or float64 - // signed value then retrieve the next part - // of the expression and add it to the right. - - if rhs == nil { - rhs, err = p.parseExpr() - if err != nil { - return nil, err - } - } - - // Find the right place in the tree to add the - // new expression, by descending the right side - // of the tree until we reach the last binary - // expression, or until we reach an expression - // whose operator precendence >= this precedence. - - for node := root; ; { - - if r, ok := rhs.(*BinaryExpression); ok { - - if r.Op.precedence() < tok.precedence() { - - r.LHS = &BinaryExpression{ - LHS: root.RHS, - Op: tok, - RHS: r.LHS, - } - - node.RHS = rhs - - break - - } - - } - - r, ok := node.RHS.(*BinaryExpression) - - if !ok || r.Op.precedence() <= tok.precedence() { - - node.RHS = &BinaryExpression{ - LHS: node.RHS, - Op: tok, - RHS: rhs, - } - - break - - } - - node = r - - } - - } - - return nil, nil - -} - -func (p *parser) parsePart() (exp Expr, err error) { - - toks := []Token{ - MUL, EXPR, IDENT, THING, MODEL, - NULL, VOID, EMPTY, MISSING, - TRUE, FALSE, STRING, REGION, NUMBER, DOUBLE, REGEX, - DATE, TIME, DURATION, JSON, ARRAY, PARAM, LPAREN, IF, - } - - tok, lit, _ := p.scan() - - // We need to declare the type up here instead - // of at the bottom, as the held value might - // be overwritten by the next token scan. - - exp, err = p.declare(tok, lit) - if err != nil { - return nil, err - } - - // If the current token is a IF word clause - // then we will parse anything from here on - // as an IF expression clause. - - if is(tok, IF) { - return p.parseIfel() - } - - // If the current token is a left parenthesis - // bracket, then we will parse this complete - // expression part as a subquery. - - if is(tok, LPAREN) { - return p.parseSubq() - } - - // If the next token is a left parenthesis - // bracket, then we will parse this complete - // expression part as a function call. - - if _, _, exi := p.mightBe(LPAREN); exi { - return p.parseCall(lit) - } - - // If this expression is not a subquery or a - // function call, then check to see if the - // token is in the list of allowed tokens. - - if !in(tok, toks) { - err = &ParseError{Found: lit, Expected: []string{"expression"}} - } - - return - -} - -func (p *parser) parseIfel() (exp *SubExpression, err error) { - - exp = &SubExpression{} - - exp.Expr, err = p.parseIfelseStatement() - if err != nil { - return nil, err - } - - return - -} - -func (p *parser) parseSubq() (exp *SubExpression, err error) { - - exp = &SubExpression{} - - tok, _, _ := p.mightBe(SELECT, CREATE, UPDATE, DELETE, RELATE, INSERT, UPSERT) - - switch tok { - case SELECT: - exp.Expr, err = p.parseSelectStatement() - case CREATE: - p.buf.rw = true - exp.Expr, err = p.parseCreateStatement() - case UPDATE: - p.buf.rw = true - exp.Expr, err = p.parseUpdateStatement() - case DELETE: - p.buf.rw = true - exp.Expr, err = p.parseDeleteStatement() - case RELATE: - p.buf.rw = true - exp.Expr, err = p.parseRelateStatement() - case INSERT: - p.buf.rw = true - exp.Expr, err = p.parseInsertStatement() - case UPSERT: - p.buf.rw = true - exp.Expr, err = p.parseUpsertStatement() - default: - exp.Expr, err = p.parseExpr() - } - - if err != nil { - return nil, err - } - - _, _, err = p.shouldBe(RPAREN) - - return - -} - -func (p *parser) parseMult() (exp *MultExpression, err error) { - - exp = &MultExpression{} - - if _, _, err = p.shouldBe(LPAREN); err != nil { - return nil, err - } - - for { - - var stm Expr - - tok, _, _ := p.mightBe(IF, RUN, CREATE, UPDATE, DELETE, RELATE, INSERT, UPSERT) - - switch tok { - case IF: - stm, err = p.parseIfel() - case RUN: - stm, err = p.parseRunStatement() - case CREATE: - p.buf.rw = true - stm, err = p.parseCreateStatement() - case UPDATE: - p.buf.rw = true - stm, err = p.parseUpdateStatement() - case DELETE: - p.buf.rw = true - stm, err = p.parseDeleteStatement() - case RELATE: - p.buf.rw = true - stm, err = p.parseRelateStatement() - case INSERT: - p.buf.rw = true - stm, err = p.parseInsertStatement() - case UPSERT: - p.buf.rw = true - stm, err = p.parseUpsertStatement() - } - - exp.Expr = append(exp.Expr, stm) - - if _, _, exi := p.mightBe(SEMICOLON); !exi { - break - } - - } - - if _, _, err = p.shouldBe(RPAREN); err != nil { - return nil, err - } - - return - -} - -func (p *parser) parseCall(name string) (fnc *FuncExpression, err error) { - - fnc = &FuncExpression{Name: name} - - // Check to see if this is an aggregate - // function, and if it is then mark it, - // so we can process it correcyly in the - // 'iterator' and 'document' layers. - - if _, ok := aggrs[name]; ok { - fnc.Aggr = true - } - - // Check to see if the immediate token - // is a right parenthesis bracket, and if - // it is then this function has no args. - - if _, _, exi := p.mightBe(RPAREN); !exi { - - for { - - var arg Expr - - arg, err = p.parseExpr() - if err != nil { - return nil, err - } - - // Append the single expression to the array - // of function argument expressions. - - fnc.Args = append(fnc.Args, arg) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - _, _, err = p.shouldBe(RPAREN) - - } - - // Check to see if the used function name is - // valid according to the currently supported - // functions. If not then return an error. - - if _, ok := funcs[fnc.Name]; !ok { - - return nil, &ParseError{ - Found: fmt.Sprintf("%s()", name), - Expected: []string{"valid function name"}, - } - - } - - // Check to see if this function is allowed to - // have an undefined number of arguments, and - // if it is then skip argument checking. - - if _, ok := funcs[fnc.Name][-1]; ok { - return - } - - // Check to see if the number of arguments - // is correct for the specified function name, - // and if not, then return an error. - - if _, ok := funcs[fnc.Name][len(fnc.Args)]; !ok { - - s, a, t := "", []int{}, len(funcs[fnc.Name]) - - for i := range funcs[fnc.Name] { - a = append(a, i) - } - - sort.Ints(a) - - for i := 0; i < t; i++ { - switch { - case i > 0 && i == t-1: - s = s + " or " - case i > 0: - s = s + ", " - } - s = s + fmt.Sprintf("%d", a[i]) - } - - switch t { - case 1: - s = s + " argument" - default: - s = s + " arguments" - } - - return nil, &ParseError{ - Found: fmt.Sprintf("%s() with %d arguments", fnc.Name, len(fnc.Args)), - Expected: []string{s}, - } - - } - - return - -} - -func (p *parser) parsePath(expr ...Expr) (path *PathExpression, err error) { - - defer func() { - if val, ok := path.Expr[len(path.Expr)-1].(*JoinExpression); ok { - if val.Join == DOT { - err = &ParseError{ - Found: fmt.Sprintf("."), - Expected: []string{"field expression"}, - } - } - } - }() - - path = &PathExpression{} - - // Take the previosuly scanned expression - // and append it to the path expression - // tree as the first item. - - for _, e := range expr { - switch v := e.(type) { - case Token: - path.Expr = append(path.Expr, &JoinExpression{Join: v}) - default: - path.Expr = append(path.Expr, &PartExpression{Part: v}) - } - } - - // If the last expression passed in was a - // path joiner (->, <-, or <->), then we - // need to process a path part first. - - if _, ok := expr[len(expr)-1].(Token); ok { - - var part Expr - - part, err = p.parseStep() - if err != nil { - return - } - - if part == nil { - return - } - - path.Expr = append(path.Expr, &PartExpression{Part: part}) - - } - - for { - - var join Expr - var part Expr - - // We expect the next token to be a join - // operator (->, <-, or <->), otherwise we - // are at the end of the path and will - // ignore it and return. - - join, err = p.parseJoin() - if err != nil { - return - } - - if join == nil { - return - } - - path.Expr = append(path.Expr, &JoinExpression{Join: join.(Token)}) - - // We expect the next token to be a path - // part identifier, otherwise we are at - // the end of the path and will ignore it - // and return. - - part, err = p.parseStep() - if err != nil { - return - } - - if part == nil { - return - } - - path.Expr = append(path.Expr, &PartExpression{Part: part}) - - } - -} - -func (p *parser) parseJoin() (exp Expr, err error) { - - toks := []Token{ - DOT, OEDGE, IEDGE, BEDGE, - } - - tok, _, _ := p.scan() - - if !in(tok, toks) { - p.unscan() - return - } - - return tok, err - -} - -func (p *parser) parseStep() (exp Expr, err error) { - - toks := []Token{ - QMARK, IDENT, THING, LPAREN, EXPR, MUL, - } - - tok, lit, _ := p.scan() - - // We need to declare the type up here instead - // of at the bottom, as the held value might - // be overwritten by the next token scan. - - exp, err = p.declare(tok, lit) - if err != nil { - return nil, err - } - - // If the current token is a left parenthesis - // bracket, then we will parse this complete - // expression part as a subquery. - - if is(tok, LPAREN) { - return p.parseSubp() - } - - // If this expression is not a sub-path - // expression, then check to see if the - // token is in the list of allowed tokens. - - if !in(tok, toks) { - p.unscan() - exp = nil - } - - return - -} - -func (p *parser) parseSubp() (stmt *SubpExpression, err error) { - - stmt = &SubpExpression{} - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - if _, _, exi := p.mightBe(AS); exi { - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - } - - if stmt.Cond, err = p.parseCond(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(RPAREN); err != nil { - return nil, err - } - - return - -} diff --git a/sql/field.go b/sql/field.go deleted file mode 100644 index 8762be08..00000000 --- a/sql/field.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineFieldStatement() (stmt *DefineFieldStatement, err error) { - - stmt = &DefineFieldStatement{} - - if stmt.Name, err = p.parseIdiom(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - for { - - tok, _, exi := p.mightBe(TYPE, VALUE, ASSERT, PRIORITY, PERMISSIONS) - if !exi { - break - } - - if is(tok, TYPE) { - if stmt.Type, stmt.Kind, err = p.parseType(); err != nil { - return nil, err - } - } - - if is(tok, VALUE) { - if stmt.Value, err = p.parseExpr(); err != nil { - return nil, err - } - } - - if is(tok, ASSERT) { - if stmt.Assert, err = p.parseExpr(); err != nil { - return nil, err - } - } - - if is(tok, PRIORITY) { - if stmt.Priority, err = p.parsePriority(); err != nil { - return nil, err - } - } - - if is(tok, PERMISSIONS) { - if stmt.Perms, err = p.parsePerms(); err != nil { - return nil, err - } - } - - } - - return - -} - -func (p *parser) parseRemoveFieldStatement() (stmt *RemoveFieldStatement, err error) { - - stmt = &RemoveFieldStatement{} - - if stmt.Name, err = p.parseIdiom(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/funcs.go b/sql/funcs.go deleted file mode 100644 index 90ef0549..00000000 --- a/sql/funcs.go +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -var rolls = map[string]bool{ - - "distinct": true, - - // Count implementation - - "count": true, - "count.if": true, - "count.not": true, - - // Math implementation - - "math.max": true, - "math.mean": true, - "math.min": true, - "math.stddev": true, - "math.sum": true, - "math.variance": true, -} - -var aggrs = map[string]bool{ - - "distinct": true, - - // Count implementation - - "count": true, - "count.if": true, - "count.not": true, - - // Math implementation - - "math.bottom": true, - "math.geometricmean": true, - "math.harmonicmean": true, - "math.interquartile": true, - "math.max": true, - "math.mean": true, - "math.median": true, - "math.midhinge": true, - "math.min": true, - "math.mode": true, - "math.nearestrank": true, - "math.percentile": true, - "math.sample": true, - "math.spread": true, - "math.stddev": true, - "math.sum": true, - "math.top": true, - "math.trimean": true, - "math.variance": true, -} - -var funcs = map[string]map[int]interface{}{ - - "array": {-1: nil}, - "batch": {2: nil}, - "difference": {-1: nil}, - "distinct": {1: nil}, - "either": {-1: nil}, - "get": {2: nil}, - "if": {3: nil}, - "intersect": {-1: nil}, - "model": {2: nil, 3: nil, 4: nil}, - "regex": {1: nil}, - "table": {1: nil}, - "thing": {2: nil}, - "union": {-1: nil}, - - // Count implementation - "count": {1: nil}, - "count.if": {2: nil}, - "count.not": {2: nil}, - - // Purge implementation - "purge": {1: nil}, - "purge.if": {2: nil}, - "purge.not": {2: nil}, - - // Geo implementation - "geo.point": {1: nil, 2: nil}, - "geo.circle": {2: nil}, - "geo.polygon": {-1: nil}, - "geo.contains": {2: nil}, - "geo.distance": {2: nil}, - "geo.inside": {2: nil}, - "geo.intersects": {2: nil}, - "geo.hash.decode": {1: nil}, - "geo.hash.encode": {2: nil}, - - // Http implementation - "http.head": {1: nil, 2: nil}, - "http.get": {1: nil, 2: nil}, - "http.put": {1: nil, 2: nil, 3: nil}, - "http.post": {1: nil, 2: nil, 3: nil}, - "http.patch": {1: nil, 2: nil, 3: nil}, - "http.delete": {1: nil, 2: nil}, - "http.async.head": {1: nil, 2: nil}, - "http.async.get": {1: nil, 2: nil}, - "http.async.put": {1: nil, 2: nil, 3: nil}, - "http.async.post": {1: nil, 2: nil, 3: nil}, - "http.async.patch": {1: nil, 2: nil, 3: nil}, - "http.async.delete": {1: nil, 2: nil}, - - // Math implementation - "math.abs": {1: nil}, - "math.bottom": {2: nil}, - "math.ceil": {1: nil}, - "math.correlation": {2: nil}, - "math.covariance": {2: nil}, - "math.fixed": {2: nil}, - "math.floor": {1: nil}, - "math.geometricmean": {1: nil}, - "math.harmonicmean": {1: nil}, - "math.interquartile": {1: nil}, - "math.max": {1: nil}, - "math.mean": {1: nil}, - "math.median": {1: nil}, - "math.midhinge": {1: nil}, - "math.min": {1: nil}, - "math.mode": {1: nil}, - "math.nearestrank": {2: nil}, - "math.percentile": {2: nil}, - "math.round": {1: nil}, - "math.sample": {2: nil}, - "math.spread": {1: nil}, - "math.sqrt": {1: nil}, - "math.stddev": {1: nil}, - "math.sum": {1: nil}, - "math.top": {2: nil}, - "math.trimean": {1: nil}, - "math.variance": {1: nil}, - - // String implementation - "string.concat": {-1: nil}, - "string.contains": {2: nil}, - "string.endsWith": {2: nil}, - "string.format": {-1: nil}, - "string.includes": {2: nil}, - "string.join": {-1: nil}, - "string.length": {1: nil}, - "string.lowercase": {1: nil}, - "string.repeat": {2: nil}, - "string.replace": {3: nil}, - "string.reverse": {1: nil}, - "string.search": {2: nil}, - "string.slice": {3: nil}, - "string.slug": {1: nil, 2: nil}, - "string.split": {2: nil}, - "string.startsWith": {2: nil}, - "string.substr": {3: nil}, - "string.trim": {1: nil}, - "string.uppercase": {1: nil}, - "string.words": {1: nil}, - - // Hash implementation - "hash.md5": {1: nil}, - "hash.sha1": {1: nil}, - "hash.sha256": {1: nil}, - "hash.sha512": {1: nil}, - - // Time implementation - "time.now": {0: nil}, - "time.add": {2: nil}, - "time.age": {2: nil}, - "time.floor": {2: nil}, - "time.round": {2: nil}, - "time.day": {0: nil, 1: nil}, - "time.hour": {0: nil, 1: nil}, - "time.mins": {0: nil, 1: nil}, - "time.month": {0: nil, 1: nil}, - "time.nano": {0: nil, 1: nil}, - "time.secs": {0: nil, 1: nil}, - "time.unix": {0: nil, 1: nil}, - "time.wday": {0: nil, 1: nil}, - "time.week": {0: nil, 1: nil}, - "time.yday": {0: nil, 1: nil}, - "time.year": {0: nil, 1: nil}, - - // Url implementation - "url.domain": {1: nil}, - "url.host": {1: nil}, - "url.port": {1: nil}, - "url.path": {1: nil}, - - // Email implementation - "email.user": {1: nil}, - "email.domain": {1: nil}, - "email.valid": {1: nil}, - - // Bcrypt implementation - "bcrypt.compare": {2: nil}, - "bcrypt.generate": {1: nil}, - - // Scrypt implementation - "scrypt.compare": {2: nil}, - "scrypt.generate": {1: nil}, - - // Check implementation - "is.alpha": {1: nil}, - "is.alphanum": {1: nil}, - "is.ascii": {1: nil}, - "is.domain": {1: nil}, - "is.email": {1: nil}, - "is.hexadecimal": {1: nil}, - "is.latitude": {1: nil}, - "is.longitude": {1: nil}, - "is.numeric": {1: nil}, - "is.semver": {1: nil}, - "is.uuid": {1: nil}, - - // Random implementation - "rand": {0: nil}, - "guid": {0: nil}, - "uuid": {0: nil}, - "rand.bool": {0: nil}, - "rand.guid": {0: nil}, - "rand.uuid": {0: nil}, - "rand.enum": {-1: nil}, - "rand.time": {0: nil, 2: nil}, - "rand.string": {0: nil, 1: nil, 2: nil}, - "rand.integer": {0: nil, 2: nil}, - "rand.decimal": {0: nil, 2: nil}, - "rand.sentence": {0: nil, 2: nil}, - "rand.paragraph": {0: nil, 2: nil}, - "rand.person.email": {0: nil}, - "rand.person.phone": {0: nil}, - "rand.person.fullname": {0: nil}, - "rand.person.firstname": {0: nil}, - "rand.person.lastname": {0: nil}, - "rand.person.username": {0: nil}, - "rand.person.jobtitle": {0: nil}, - "rand.company.name": {0: nil}, - "rand.company.industry": {0: nil}, - "rand.location.name": {0: nil}, - "rand.location.address": {0: nil}, - "rand.location.street": {0: nil}, - "rand.location.city": {0: nil}, - "rand.location.state": {0: nil}, - "rand.location.county": {0: nil}, - "rand.location.zipcode": {0: nil}, - "rand.location.postcode": {0: nil}, - "rand.location.country": {0: nil}, - "rand.location.altitude": {0: nil}, - "rand.location.latitude": {0: nil}, - "rand.location.longitude": {0: nil}, -} diff --git a/sql/gen.go b/sql/gen.go deleted file mode 100644 index 24d7e677..00000000 --- a/sql/gen.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -//go:generate go get -u github.com/abcum/tmpl -//go:generate tmpl -file=kill.gen.json kill.gen.go.tmpl -//go:generate tmpl -file=rdwr.gen.json rdwr.gen.go.tmpl - -//go:generate go get -u github.com/ugorji/go/codec/codecgen -//go:generate codecgen -o ast.gen.go ast.go diff --git a/sql/ifelse.go b/sql/ifelse.go deleted file mode 100644 index d7d8efad..00000000 --- a/sql/ifelse.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseIfelseStatement() (stmt *IfelseStatement, err error) { - - grw := p.buf.rw - - p.buf.rw = false - - defer func() { - p.buf.rw = grw - }() - - stmt = &IfelseStatement{} - - for { - - var tok Token - - if cond, err := p.parseExpr(); err != nil { - return nil, err - } else { - stmt.Cond = append(stmt.Cond, cond) - } - - if _, _, err = p.shouldBe(THEN); err != nil { - return nil, err - } - - if then, err := p.parseExpr(); err != nil { - return nil, err - } else { - stmt.Then = append(stmt.Then, then) - } - - // Check to see if the next token is an - // ELSE keyword and if it is then check to - // see if there is another if statement. - - if tok, _, err = p.shouldBe(ELSE, END); err != nil { - return nil, err - } - - if tok == END { - return - } - - if tok == ELSE { - if _, _, exi := p.mightBe(IF); !exi { - break - } - } - - } - - // Check to see if the next token is an - // ELSE keyword and if it is then check to - // see if there is another if statement. - - if then, err := p.parseExpr(); err != nil { - return nil, err - } else { - stmt.Else = then - } - - if _, _, err = p.shouldBe(END); err != nil { - return nil, err - } - - // If this query has any subqueries which - // need to alter the database then mark - // this query as a writeable statement. - - stmt.RW = p.buf.rw - - return - -} diff --git a/sql/index.go b/sql/index.go deleted file mode 100644 index 454d5187..00000000 --- a/sql/index.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineIndexStatement() (stmt *DefineIndexStatement, err error) { - - stmt = &DefineIndexStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(COLUMNS); err != nil { - return nil, err - } - - if stmt.Cols, err = p.parseIdioms(); err != nil { - return nil, err - } - - _, _, stmt.Uniq = p.mightBe(UNIQUE) - - return - -} - -func (p *parser) parseRemoveIndexStatement() (stmt *RemoveIndexStatement, err error) { - - stmt = &RemoveIndexStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/info.go b/sql/info.go deleted file mode 100644 index a7308e6a..00000000 --- a/sql/info.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseInfoStatement() (stmt *InfoStatement, err error) { - - stmt = &InfoStatement{} - - if _, _, err = p.shouldBe(FOR); err != nil { - return nil, err - } - - if stmt.Kind, _, err = p.shouldBe(ALL, NAMESPACE, DATABASE, SCOPE, TABLE, NS, DB); err != nil { - return nil, err - } - - if is(stmt.Kind, SCOPE) || is(stmt.Kind, TABLE) { - if stmt.What, err = p.parseIdent(); err != nil { - return nil, err - } - } - - return - -} diff --git a/sql/insert.go b/sql/insert.go deleted file mode 100644 index 9f9501f1..00000000 --- a/sql/insert.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseInsertStatement() (stmt *InsertStatement, err error) { - - stmt = &InsertStatement{} - - if stmt.Data, err = p.parseExpr(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(INTO); err != nil { - return nil, err - } - - _, _, _ = p.mightBe(TABLE) - - if stmt.Into, err = p.parseTable(); err != nil { - return nil, err - } - - if stmt.Echo, err = p.parseEcho(AFTER); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/kill.gen.go b/sql/kill.gen.go deleted file mode 100644 index 487646fd..00000000 --- a/sql/kill.gen.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by https://github.com/abcum/tmpl -// Source file: kill.gen.go.tmpl -// DO NOT EDIT! - -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "time" -) - -func (s *SelectStatement) Duration() time.Duration { - return s.Timeout -} - -func (s *CreateStatement) Duration() time.Duration { - return s.Timeout -} - -func (s *UpdateStatement) Duration() time.Duration { - return s.Timeout -} - -func (s *DeleteStatement) Duration() time.Duration { - return s.Timeout -} - -func (s *RelateStatement) Duration() time.Duration { - return s.Timeout -} - -func (s *InsertStatement) Duration() time.Duration { - return s.Timeout -} - -func (s *UpsertStatement) Duration() time.Duration { - return s.Timeout -} diff --git a/sql/kill.gen.go.tmpl b/sql/kill.gen.go.tmpl deleted file mode 100644 index b23fb6a9..00000000 --- a/sql/kill.gen.go.tmpl +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "time" -) - -{{with $types := .}}{{range $k := $types}} - -func (s *{{$k.name}}Statement) Duration() time.Duration { - return s.Timeout -} - -{{end}}{{end}} diff --git a/sql/kill.gen.json b/sql/kill.gen.json deleted file mode 100644 index 067d9045..00000000 --- a/sql/kill.gen.json +++ /dev/null @@ -1,9 +0,0 @@ -[ - { "name": "Select" }, - { "name": "Create" }, - { "name": "Update" }, - { "name": "Delete" }, - { "name": "Relate" }, - { "name": "Insert" }, - { "name": "Upsert" } -] diff --git a/sql/kill_test.go b/sql/kill_test.go deleted file mode 100644 index 82635228..00000000 --- a/sql/kill_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Code generated by https://github.com/abcum/tmpl -// Source file: kill.gen.go.tmpl -// DO NOT EDIT! - -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestKill(t *testing.T) { - - Convey("SelectStatement should have duration", t, func() { - So((&SelectStatement{}).Duration(), ShouldEqual, 0) - So((&SelectStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - - Convey("CreateStatement should have duration", t, func() { - So((&CreateStatement{}).Duration(), ShouldEqual, 0) - So((&CreateStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - - Convey("UpdateStatement should have duration", t, func() { - So((&UpdateStatement{}).Duration(), ShouldEqual, 0) - So((&UpdateStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - - Convey("DeleteStatement should have duration", t, func() { - So((&DeleteStatement{}).Duration(), ShouldEqual, 0) - So((&DeleteStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - - Convey("RelateStatement should have duration", t, func() { - So((&RelateStatement{}).Duration(), ShouldEqual, 0) - So((&RelateStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - - Convey("InsertStatement should have duration", t, func() { - So((&InsertStatement{}).Duration(), ShouldEqual, 0) - So((&InsertStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - - Convey("UpsertStatement should have duration", t, func() { - So((&UpsertStatement{}).Duration(), ShouldEqual, 0) - So((&UpsertStatement{Timeout: 1 * time.Second}).Duration(), ShouldEqual, 1*time.Second) - }) - -} diff --git a/sql/let.go b/sql/let.go deleted file mode 100644 index b3d19ce9..00000000 --- a/sql/let.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseLetStatement() (stmt *LetStatement, err error) { - - grw := p.buf.rw - - p.buf.rw = false - - defer func() { - p.buf.rw = grw - }() - - stmt = &LetStatement{} - - // The first part of a LET expression must - // always be an identifier, specifying a - // variable name to set. - - stmt.Name, err = p.parseParam() - if err != nil { - return nil, err - } - - // The next query part must always be a = - // operator, as this is a LET expression - // and not a binary expression. - - _, _, err = p.shouldBe(EQ) - if err != nil { - return nil, err - } - - // The next query part can be any expression - // including a parenthesised expression or a - // binary expression so handle accordingly. - - stmt.What, err = p.parseExpr() - if err != nil { - return nil, err - } - - // If this query has any subqueries which - // need to alter the database then mark - // this query as a writeable statement. - - stmt.RW = p.buf.rw - - return - -} diff --git a/sql/live.go b/sql/live.go deleted file mode 100644 index f1ea43b4..00000000 --- a/sql/live.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseLiveStatement() (stmt *LiveStatement, err error) { - - stmt = &LiveStatement{} - - _, _, err = p.shouldBe(SELECT) - if err != nil { - return nil, err - } - - _, _, stmt.Diff = p.mightBe(DIFF) - - if stmt.Diff == false { - - if stmt.Expr, err = p.parseFields(); err != nil { - return nil, err - } - - } - - _, _, err = p.shouldBe(FROM) - if err != nil { - return nil, err - } - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - if stmt.Cond, err = p.parseCond(); err != nil { - return nil, err - } - - if stmt.Fetch, err = p.parseFetch(); err != nil { - return nil, err - } - - return - -} - -func (p *parser) parseKillStatement() (stmt *KillStatement, err error) { - - stmt = &KillStatement{} - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/login.go b/sql/login.go deleted file mode 100644 index cf34db75..00000000 --- a/sql/login.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineLoginStatement() (stmt *DefineLoginStatement, err error) { - - stmt = &DefineLoginStatement{} - - if stmt.User, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.Kind, _, err = p.shouldBe(NAMESPACE, DATABASE); err != nil { - return nil, err - } - - tok, _, err := p.shouldBe(PASSWORD, PASSHASH) - if err != nil { - return nil, err - } - - if is(tok, PASSWORD) { - if stmt.Pass, err = p.parseBinary(); err != nil { - return nil, err - } - } - - if is(tok, PASSHASH) { - if stmt.Hash, err = p.parseBinary(); err != nil { - return nil, err - } - } - - return - -} - -func (p *parser) parseRemoveLoginStatement() (stmt *RemoveLoginStatement, err error) { - - stmt = &RemoveLoginStatement{} - - if stmt.User, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.Kind, _, err = p.shouldBe(NAMESPACE, DATABASE); err != nil { - return nil, err - } - - return - -} diff --git a/sql/namespace.go b/sql/namespace.go deleted file mode 100644 index 8b39f9b4..00000000 --- a/sql/namespace.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineNamespaceStatement() (stmt *DefineNamespaceStatement, err error) { - - stmt = &DefineNamespaceStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - return - -} - -func (p *parser) parseRemoveNamespaceStatement() (stmt *RemoveNamespaceStatement, err error) { - - stmt = &RemoveNamespaceStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/option.go b/sql/option.go deleted file mode 100644 index f16b3eac..00000000 --- a/sql/option.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseOptionStatement() (stmt *OptStatement, err error) { - - stmt = &OptStatement{What: true} - - _, lit, err := p.shouldBe(IDENT, STRING) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"name"}} - } - - // The first part of a SET expression must - // always be an identifier, specifying a - // variable name to set. - - stmt.Name = lit - - // The next part might be a = operator, - // which mist be followed by a TRUE or - // FALSE boolean value. - - if _, _, exi := p.mightBe(EQ); exi { - - stmt.What, err = p.parseBool() - if err != nil { - return nil, err - } - - } - - return - -} diff --git a/sql/parser.go b/sql/parser.go deleted file mode 100644 index 804319ab..00000000 --- a/sql/parser.go +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "bytes" - "io" - "strings" -) - -// parser represents a parser. -type parser struct { - s *scanner - buf struct { - n int // buffer size - rw bool // writeable - tok Token // last read token - lit string // last read literal - val interface{} // Last read value - } -} - -// Parse parses sql from a []byte, string, or io.Reader. -func Parse(i interface{}) (*Query, error) { - - switch x := i.(type) { - default: - return nil, &EmptyError{} - case []byte: - return parseBytes(x) - case string: - return parseString(x) - case io.Reader: - return parseBuffer(x) - } - -} - -// newParser returns a new instance of Parser. -func newParser() *parser { - return &parser{} -} - -// parseBytes parses a byte array. -func parseBytes(i []byte) (*Query, error) { - p := newParser() - r := bytes.NewReader(i) - p.s = newScanner(r) - return p.parse() -} - -// parseString parses a string. -func parseString(i string) (*Query, error) { - p := newParser() - r := strings.NewReader(i) - p.s = newScanner(r) - return p.parse() -} - -// parseBuffer parses a buffer. -func parseBuffer(r io.Reader) (*Query, error) { - p := newParser() - p.s = newScanner(r) - return p.parse() -} - -// parse parses single or multiple SQL queries. -func (p *parser) parse() (*Query, error) { - return p.parseMulti() -} - -// parseMulti parses multiple SQL SELECT statements. -func (p *parser) parseMulti() (*Query, error) { - - var semi bool - - var stmts Statements - - for { - - // If the next token is an EOF then - // check to see if the query is empty - // or return the parsed statements. - - if _, _, exi := p.mightBe(EOF); exi { - if len(stmts) == 0 { - return nil, new(EmptyError) - } - return &Query{Statements: stmts}, nil - } - - // If this is a multi statement query - // and there is no semicolon separating - // the statements, then return an error. - - if len(stmts) > 0 { - switch semi { - case true: - _, _, exi := p.mightBe(SEMICOLON) - if exi { - continue - } - case false: - _, _, err := p.shouldBe(SEMICOLON) - if err != nil { - return nil, err - } - semi = true - continue - } - } - - // Parse the next token as a statement - // and append it to the statements - // array for the current sql query. - - stmt, err := p.parseSingle() - if err != nil { - return nil, err - } - - stmts = append(stmts, stmt) - - } - -} - -// parseSingle parses a single SQL SELECT statement. -func (p *parser) parseSingle() (stmt Statement, err error) { - - p.buf.rw = false - - tok, _, err := p.shouldBe( - USE, - INFO, - BEGIN, - CANCEL, - COMMIT, - IF, - LET, - RETURN, - LIVE, - KILL, - SELECT, - CREATE, - UPDATE, - DELETE, - RELATE, - INSERT, - UPSERT, - DEFINE, - REMOVE, - OPTION, - ) - - switch tok { - - case USE: - return p.parseUseStatement() - - case LET: - return p.parseLetStatement() - - case INFO: - return p.parseInfoStatement() - - case LIVE: - return p.parseLiveStatement() - case KILL: - return p.parseKillStatement() - - case BEGIN: - return p.parseBeginStatement() - case CANCEL: - return p.parseCancelStatement() - case COMMIT: - return p.parseCommitStatement() - case RETURN: - return p.parseReturnStatement() - - case IF: - return p.parseIfelseStatement() - case SELECT: - return p.parseSelectStatement() - case CREATE: - return p.parseCreateStatement() - case UPDATE: - return p.parseUpdateStatement() - case DELETE: - return p.parseDeleteStatement() - case RELATE: - return p.parseRelateStatement() - case INSERT: - return p.parseInsertStatement() - case UPSERT: - return p.parseUpsertStatement() - - case DEFINE: - return p.parseDefineStatement() - case REMOVE: - return p.parseRemoveStatement() - case OPTION: - return p.parseOptionStatement() - - default: - return nil, err - - } - -} - -func (p *parser) mightBe(expected ...Token) (tok Token, lit string, found bool) { - - tok, lit, _ = p.scan() - - if found = in(tok, expected); !found { - p.unscan() - } - - return - -} - -func (p *parser) shouldBe(expected ...Token) (tok Token, lit string, err error) { - - tok, lit, _ = p.scan() - - if !in(tok, expected) { - p.unscan() - err = &ParseError{Found: lit, Expected: lookup(expected)} - } - - return - -} - -// scan scans the next non-whitespace token. -func (p *parser) scan() (tok Token, lit string, val interface{}) { - - tok, lit, val = p.seek() - - for { - if tok == WS { - tok, lit, val = p.seek() - } else { - break - } - } - - return - -} - -func (p *parser) hold(tok Token) (val interface{}) { - if tok == p.buf.tok { - return p.buf.val - } - return nil -} - -// seek returns the next token from the underlying scanner. -// If a token has been unscanned then read that instead. -func (p *parser) seek() (tok Token, lit string, val interface{}) { - - // If we have a token on the buffer, then return it. - if p.buf.n != 0 { - p.buf.n = 0 - return p.buf.tok, p.buf.lit, p.buf.val - } - - // Otherwise read the next token from the scanner. - tok, lit, val = p.s.scan() - - // Save it to the buffer in case we unscan later. - p.buf.tok, p.buf.lit, p.buf.val = tok, lit, val - - return - -} - -// unscan pushes the previously read token back onto the buffer. -func (p *parser) unscan() { - p.buf.n = 1 -} diff --git a/sql/perms.go b/sql/perms.go deleted file mode 100644 index a87dfa4d..00000000 --- a/sql/perms.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parsePerms() (exp *PermExpression, err error) { - - exp = &PermExpression{ - Select: false, - Create: false, - Update: false, - Delete: false, - } - - tok, _, err := p.shouldBe(FOR, NONE, FULL, WHERE) - if err != nil { - return exp, err - } - - if is(tok, NONE, FULL, WHERE) { - - var expr Expr - - switch tok { - case FULL: - expr = true - case NONE: - expr = false - case WHERE: - if expr, err = p.parseExpr(); err != nil { - return exp, err - } - } - - exp.Select = expr - exp.Create = expr - exp.Update = expr - exp.Delete = expr - - return - - } - - if is(tok, FOR) { - - for { - - var expr Expr - var when []Token - - for { - tok, _, err := p.shouldBe(SELECT, CREATE, UPDATE, DELETE) - if err != nil { - return exp, err - } - when = append(when, tok) - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - } - - tok, _, err := p.shouldBe(FULL, NONE, WHERE) - if err != nil { - return exp, err - } - - switch tok { - case FULL: - expr = true - case NONE: - expr = false - case WHERE: - if expr, err = p.parseExpr(); err != nil { - return exp, err - } - } - - for _, w := range when { - switch w { - case SELECT: - exp.Select = expr - case CREATE: - exp.Create = expr - case UPDATE: - exp.Update = expr - case DELETE: - exp.Delete = expr - } - } - - if _, _, exi := p.mightBe(FOR); !exi { - break - } - - } - - } - - return - -} diff --git a/sql/rdwr.gen.go b/sql/rdwr.gen.go deleted file mode 100644 index ed0a5157..00000000 --- a/sql/rdwr.gen.go +++ /dev/null @@ -1,143 +0,0 @@ -// Code generated by https://github.com/abcum/tmpl -// Source file: rdwr.gen.go.tmpl -// DO NOT EDIT! - -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (s *InfoStatement) Writeable() bool { - return false -} - -func (s *LetStatement) Writeable() bool { - return s.RW -} - -func (s *LiveStatement) Writeable() bool { - return true -} - -func (s *KillStatement) Writeable() bool { - return true -} - -func (s *ReturnStatement) Writeable() bool { - return s.RW -} - -func (s *IfelseStatement) Writeable() bool { - return s.RW -} - -func (s *SelectStatement) Writeable() bool { - return s.RW -} - -func (s *CreateStatement) Writeable() bool { - return true -} - -func (s *UpdateStatement) Writeable() bool { - return true -} - -func (s *DeleteStatement) Writeable() bool { - return true -} - -func (s *RelateStatement) Writeable() bool { - return true -} - -func (s *InsertStatement) Writeable() bool { - return true -} - -func (s *UpsertStatement) Writeable() bool { - return true -} - -func (s *DefineNamespaceStatement) Writeable() bool { - return true -} - -func (s *RemoveNamespaceStatement) Writeable() bool { - return true -} - -func (s *DefineDatabaseStatement) Writeable() bool { - return true -} - -func (s *RemoveDatabaseStatement) Writeable() bool { - return true -} - -func (s *DefineLoginStatement) Writeable() bool { - return true -} - -func (s *RemoveLoginStatement) Writeable() bool { - return true -} - -func (s *DefineTokenStatement) Writeable() bool { - return true -} - -func (s *RemoveTokenStatement) Writeable() bool { - return true -} - -func (s *DefineScopeStatement) Writeable() bool { - return true -} - -func (s *RemoveScopeStatement) Writeable() bool { - return true -} - -func (s *DefineTableStatement) Writeable() bool { - return true -} - -func (s *RemoveTableStatement) Writeable() bool { - return true -} - -func (s *DefineEventStatement) Writeable() bool { - return true -} - -func (s *RemoveEventStatement) Writeable() bool { - return true -} - -func (s *DefineFieldStatement) Writeable() bool { - return true -} - -func (s *RemoveFieldStatement) Writeable() bool { - return true -} - -func (s *DefineIndexStatement) Writeable() bool { - return true -} - -func (s *RemoveIndexStatement) Writeable() bool { - return true -} diff --git a/sql/rdwr.gen.go.tmpl b/sql/rdwr.gen.go.tmpl deleted file mode 100644 index bdec1167..00000000 --- a/sql/rdwr.gen.go.tmpl +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -{{with $types := .}}{{range $k := $types}} - -func (s *{{$k.name}}Statement) Writeable() bool { - return {{if $k.a}}s.RW{{else}}{{if $k.y}}true{{else}}false{{end}}{{end}} -} - -{{end}}{{end}} diff --git a/sql/rdwr.gen.json b/sql/rdwr.gen.json deleted file mode 100644 index 35828e5c..00000000 --- a/sql/rdwr.gen.json +++ /dev/null @@ -1,35 +0,0 @@ -[ - { "n": true, "name": "Info" }, - - { "a": true, "name": "Let" }, - { "y": true, "name": "Live" }, - { "y": true, "name": "Kill" }, - { "a": true, "name": "Return" }, - { "a": true, "name": "Ifelse" }, - { "a": true, "name": "Select" }, - { "y": true, "name": "Create" }, - { "y": true, "name": "Update" }, - { "y": true, "name": "Delete" }, - { "y": true, "name": "Relate" }, - { "y": true, "name": "Insert" }, - { "y": true, "name": "Upsert" }, - - { "y": true, "name": "DefineNamespace" }, - { "y": true, "name": "RemoveNamespace" }, - { "y": true, "name": "DefineDatabase" }, - { "y": true, "name": "RemoveDatabase" }, - { "y": true, "name": "DefineLogin" }, - { "y": true, "name": "RemoveLogin" }, - { "y": true, "name": "DefineToken" }, - { "y": true, "name": "RemoveToken" }, - { "y": true, "name": "DefineScope" }, - { "y": true, "name": "RemoveScope" }, - { "y": true, "name": "DefineTable" }, - { "y": true, "name": "RemoveTable" }, - { "y": true, "name": "DefineEvent" }, - { "y": true, "name": "RemoveEvent" }, - { "y": true, "name": "DefineField" }, - { "y": true, "name": "RemoveField" }, - { "y": true, "name": "DefineIndex" }, - { "y": true, "name": "RemoveIndex" } -] diff --git a/sql/rdwr_test.go b/sql/rdwr_test.go deleted file mode 100644 index 8b1fdec5..00000000 --- a/sql/rdwr_test.go +++ /dev/null @@ -1,215 +0,0 @@ -// Code generated by https://github.com/abcum/tmpl -// Source file: auth.gen.go.tmpl -// DO NOT EDIT! - -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestRdwr(t *testing.T) { - - Convey("InfoStatement should rdwr correctly", t, func() { - s := &InfoStatement{} - w := s.Writeable() - So(w, ShouldEqual, false) - }) - - Convey("LetStatement should rdwr correctly", t, func() { - s := &LetStatement{RW: true} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("LiveStatement should rdwr correctly", t, func() { - s := &LiveStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("KillStatement should rdwr correctly", t, func() { - s := &KillStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("ReturnStatement should rdwr correctly", t, func() { - s := &ReturnStatement{RW: true} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("IfelseStatement should rdwr correctly", t, func() { - s := &IfelseStatement{RW: true} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("SelectStatement should rdwr correctly", t, func() { - s := &SelectStatement{RW: true} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("CreateStatement should rdwr correctly", t, func() { - s := &CreateStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("UpdateStatement should rdwr correctly", t, func() { - s := &UpdateStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DeleteStatement should rdwr correctly", t, func() { - s := &DeleteStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RelateStatement should rdwr correctly", t, func() { - s := &RelateStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("InsertStatement should rdwr correctly", t, func() { - s := &InsertStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("UpsertStatement should rdwr correctly", t, func() { - s := &UpsertStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineNamespaceStatement should rdwr correctly", t, func() { - s := &DefineNamespaceStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveNamespaceStatement should rdwr correctly", t, func() { - s := &RemoveNamespaceStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineDatabaseStatement should rdwr correctly", t, func() { - s := &DefineDatabaseStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveDatabaseStatement should rdwr correctly", t, func() { - s := &RemoveDatabaseStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineLoginStatement should rdwr correctly", t, func() { - s := &DefineLoginStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveLoginStatement should rdwr correctly", t, func() { - s := &RemoveLoginStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineTokenStatement should rdwr correctly", t, func() { - s := &DefineTokenStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveTokenStatement should rdwr correctly", t, func() { - s := &RemoveTokenStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineScopeStatement should rdwr correctly", t, func() { - s := &DefineScopeStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveScopeStatement should rdwr correctly", t, func() { - s := &RemoveScopeStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineTableStatement should rdwr correctly", t, func() { - s := &DefineTableStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveTableStatement should rdwr correctly", t, func() { - s := &RemoveTableStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineEventStatement should rdwr correctly", t, func() { - s := &DefineEventStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveEventStatement should rdwr correctly", t, func() { - s := &RemoveEventStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineFieldStatement should rdwr correctly", t, func() { - s := &DefineFieldStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveFieldStatement should rdwr correctly", t, func() { - s := &RemoveFieldStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("DefineIndexStatement should rdwr correctly", t, func() { - s := &DefineIndexStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - - Convey("RemoveIndexStatement should rdwr correctly", t, func() { - s := &RemoveIndexStatement{} - w := s.Writeable() - So(w, ShouldEqual, true) - }) - -} diff --git a/sql/relate.go b/sql/relate.go deleted file mode 100644 index 9eb0eb41..00000000 --- a/sql/relate.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseRelateStatement() (stmt *RelateStatement, err error) { - - tok := ILLEGAL - - stmt = &RelateStatement{} - - if stmt.From, err = p.parseWhat(); err != nil { - return nil, err - } - - if tok, _, err = p.shouldBe(OEDGE, IEDGE); err != nil { - return nil, err - } - - if tok == OEDGE { - - stmt.From = stmt.From - - if stmt.Type, err = p.parseTable(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(OEDGE); err != nil { - return nil, err - } - - if stmt.With, err = p.parseWhat(); err != nil { - return nil, err - } - - } - - if tok == IEDGE { - - stmt.With = stmt.From - - if stmt.Type, err = p.parseTable(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(IEDGE); err != nil { - return nil, err - } - - if stmt.From, err = p.parseWhat(); err != nil { - return nil, err - } - - } - - _, _, stmt.Uniq = p.mightBe(UNIQUE) - - if stmt.Data, err = p.parseData(); err != nil { - return nil, err - } - - if stmt.Echo, err = p.parseEcho(AFTER); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/remove.go b/sql/remove.go deleted file mode 100644 index 72a1985c..00000000 --- a/sql/remove.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseRemoveStatement() (Statement, error) { - - // Inspect the next token. - tok, _, err := p.shouldBe(NAMESPACE, DATABASE, LOGIN, TOKEN, SCOPE, TABLE, EVENT, FIELD, INDEX) - - switch tok { - case NAMESPACE: - return p.parseRemoveNamespaceStatement() - case DATABASE: - return p.parseRemoveDatabaseStatement() - case LOGIN: - return p.parseRemoveLoginStatement() - case TOKEN: - return p.parseRemoveTokenStatement() - case SCOPE: - return p.parseRemoveScopeStatement() - case TABLE: - return p.parseRemoveTableStatement() - case EVENT: - return p.parseRemoveEventStatement() - case FIELD: - return p.parseRemoveFieldStatement() - case INDEX: - return p.parseRemoveIndexStatement() - default: - return nil, err - } - -} diff --git a/sql/return.go b/sql/return.go deleted file mode 100644 index 58e002d4..00000000 --- a/sql/return.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseReturnStatement() (stmt *ReturnStatement, err error) { - - grw := p.buf.rw - - p.buf.rw = false - - defer func() { - p.buf.rw = grw - }() - - stmt = &ReturnStatement{} - - // The next query part can be any expression - // including a parenthesised expression or a - // binary expression so handle accordingly. - - stmt.What, err = p.parseWhat() - if err != nil { - return nil, err - } - - // If this query has any subqueries which - // need to alter the database then mark - // this query as a writeable statement. - - stmt.RW = p.buf.rw - - return - -} diff --git a/sql/run.go b/sql/run.go deleted file mode 100644 index 71cbe028..00000000 --- a/sql/run.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseRunStatement() (stmt *RunStatement, err error) { - - grw := p.buf.rw - - p.buf.rw = false - - defer func() { - p.buf.rw = grw - }() - - stmt = &RunStatement{} - - stmt.Expr, err = p.parseExpr() - - // If this query has any subqueries which - // need to alter the database then mark - // this query as a writeable statement. - - stmt.RW = p.buf.rw - - return - -} diff --git a/sql/scanner.go b/sql/scanner.go deleted file mode 100644 index 03b72be8..00000000 --- a/sql/scanner.go +++ /dev/null @@ -1,1068 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "bufio" - "bytes" - "io" - "regexp" - "strconv" - "strings" - "time" -) - -// scanner represents a lexical scanner. -type scanner struct { - b []rune // any runes before - a []rune // any runes after - r *bufio.Reader -} - -// newScanner returns a new instance of Scanner. -func newScanner(r io.Reader) *scanner { - return &scanner{r: bufio.NewReader(r)} -} - -// scan returns the next token and literal value. -func (s *scanner) scan() (tok Token, lit string, val interface{}) { - - // Read the next rune. - ch := s.next() - - // If we see whitespace then consume all contiguous whitespace. - if isBlank(ch) { - return s.scanBlank(ch) - } - - // If we see a letter then consume as a string. - if isLetter(ch) { - return s.scanIdiom(ch) - } - - // If we see a number then consume as a number. - if isNumber(ch) { - return s.scanNumber(ch) - } - - // Otherwise read the individual character. - switch ch { - - case eof: - return EOF, "", val - case '*': - return MUL, string(ch), val - case '×': - return MUL, string(ch), val - case '∙': - return MUL, string(ch), val - case '÷': - return DIV, string(ch), val - case ',': - return COMMA, string(ch), val - case '.': - return DOT, string(ch), val - case '@': - return s.scanThing(ch) - case '"': - return s.scanString(ch) - case '\'': - return s.scanString(ch) - case '`': - return s.scanQuoted(ch) - case '⟨': - return s.scanQuoted(ch) - case '{': - return s.scanObject(ch) - case '[': - return s.scanObject(ch) - case '$': - return s.scanParams(ch) - case ':': - return COLON, string(ch), val - case ';': - return SEMICOLON, string(ch), val - case '(': - return LPAREN, string(ch), val - case ')': - return RPAREN, string(ch), val - case '¬': - return NEQ, string(ch), val - case '≤': - return LTE, string(ch), val - case '≥': - return GTE, string(ch), val - case '~': - return MAT, string(ch), val - case '∋': - return SIN, string(ch), val - case '∌': - return SNI, string(ch), val - case '⊇': - return CONTAINSALL, string(ch), val - case '⊃': - return CONTAINSSOME, string(ch), val - case '⊅': - return CONTAINSNONE, string(ch), val - case '∈': - return INS, string(ch), val - case '∉': - return NIS, string(ch), val - case '⊆': - return ALLCONTAINEDIN, string(ch), val - case '⊂': - return SOMECONTAINEDIN, string(ch), val - case '⊄': - return NONECONTAINEDIN, string(ch), val - case '#': - return s.scanCommentSingle(ch) - case '|': - chn := s.next() - switch { - case chn == '|': - return OR, "OR", val - default: - s.undo() - return s.scanModel(ch) - } - case '&': - chn := s.next() - switch { - case chn == '&': - return AND, "AND", val - default: - s.undo() - } - case '/': - chn := s.next() - switch { - case chn == '/': - return s.scanCommentSingle(ch) - case chn == '*': - return s.scanCommentMultiple(ch) - case isNumber(chn): - s.undo() - return DIV, string(ch), val - case chn == ' ': - s.undo() - return DIV, string(ch), val - default: - s.undo() - return s.scanRegexp(ch) - } - case '=': - chn := s.next() - switch { - case chn == '~': - return MAT, "=~", val - case chn == '=': - return EEQ, "==", val - default: - s.undo() - return EQ, string(ch), val - } - case '?': - chn := s.next() - switch { - case chn == '=': - return ANY, "?=", val - case chn == '~': - return MAY, "?~", val - default: - s.undo() - return QMARK, string(ch), val - } - case '!': - chn := s.next() - switch { - case chn == '=': - if s.next() == '=' { - return NEE, "!==", val - } else { - s.undo() - return NEQ, "!=", val - } - case chn == '~': - return NAT, "!~", val - default: - s.undo() - return EXC, string(ch), val - } - case '+': - chn := s.next() - switch { - case chn == '=': - return INC, "+=", val - case isNumber(chn): - return s.scanNumber(ch, chn) - default: - s.undo() - return ADD, string(ch), val - } - case '-': - chn := s.next() - switch { - case chn == '=': - return DEC, "-=", val - case chn == '>': - return OEDGE, "->", val - case chn == '-': - return s.scanCommentSingle(ch) - case isNumber(chn): - return s.scanNumber(ch, chn) - default: - s.undo() - return SUB, string(ch), val - } - case '>': - chn := s.next() - switch { - case chn == '=': - return GTE, ">=", val - default: - s.undo() - return GT, string(ch), val - } - case '<': - chn := s.next() - switch { - case chn == '>': - return NEQ, "<>", val - case chn == '=': - return LTE, "<=", val - case chn == '-': - if s.next() == '>' { - return BEDGE, "<->", val - } else { - s.undo() - return IEDGE, "<-", val - } - default: - s.undo() - return LT, string(ch), val - } - } - - return ILLEGAL, string(ch), val - -} - -// scanBlank consumes the current rune and all contiguous whitespace. -func (s *scanner) scanBlank(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = WS - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if !isBlank(ch) { - s.undo() - break - } else { - buf.WriteRune(ch) - } - } - - return tok, buf.String(), val - -} - -// scanCommentSingle consumes the current rune and all contiguous whitespace. -func (s *scanner) scanCommentSingle(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = WS - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if ch == '\n' || ch == '\r' { - buf.WriteRune(ch) - break - } else { - buf.WriteRune(ch) - } - } - - return tok, buf.String(), val - -} - -// scanCommentMultiple consumes the current rune and all contiguous whitespace. -func (s *scanner) scanCommentMultiple(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = WS - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if ch == '*' { - if chn := s.next(); chn == '/' { - buf.WriteRune(chn) - break - } - buf.WriteRune(ch) - } else { - buf.WriteRune(ch) - } - } - - return tok, buf.String(), val - -} - -func (s *scanner) scanParams(chp ...rune) (tok Token, lit string, val interface{}) { - - tok, lit, _ = s.scanIdiom() - - if is(tok, THING) { - return ILLEGAL, lit, val - } - - if is(tok, REGION) { - return ILLEGAL, lit, val - } - - if is(tok, ILLEGAL) { - return ILLEGAL, lit, val - } - - return PARAM, lit, val - -} - -func (s *scanner) scanQuoted(chp ...rune) (tok Token, lit string, val interface{}) { - - var tbv string - var idv interface{} - - // Create a buffer - var buf bytes.Buffer - - tok, lit, _ = s.scanString(chp...) - - if is(tok, REGION) { - return ILLEGAL, lit, val - } - - if is(tok, ILLEGAL) { - return ILLEGAL, lit, val - } - - if ch := s.next(); ch == ':' { - - tbv = lit - - buf.WriteString(lit) - - buf.WriteRune(ch) - - if tok, lit, idv = s.part(); tok == ILLEGAL { - buf.WriteString(lit) - return ILLEGAL, buf.String(), val - } else { - buf.WriteString(lit) - } - - return THING, buf.String(), NewThing(tbv, idv) - - } else if ch != eof { - s.undo() - } - - return IDENT, lit, val - -} - -func (s *scanner) scanSection(chp ...rune) (tok Token, lit string, val interface{}) { - - tok, lit, _ = s.scanString(chp...) - - if is(tok, REGION) { - return ILLEGAL, lit, val - } - - if is(tok, ILLEGAL) { - return ILLEGAL, lit, val - } - - return IDENT, lit, val - -} - -// scanIdent consumes the current rune and all contiguous ident runes. -func (s *scanner) scanIdent(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = IDENT - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if isIdentChar(ch) { - buf.WriteRune(ch) - } else { - s.undo() - break - } - } - - // If the string matches a keyword then return that keyword. - if tok := keywords[strings.ToUpper(buf.String())]; tok > 0 { - return tok, buf.String(), val - } - - if val, err := time.ParseDuration(buf.String()); err == nil { - return DURATION, buf.String(), val - } - - // Otherwise return as a regular identifier. - return tok, buf.String(), val - -} - -// scanIdiom consumes the current rune and all contiguous ident runes. -func (s *scanner) scanIdiom(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = IDENT - - var tbv string - var idv interface{} - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if isIdentChar(ch) { - buf.WriteRune(ch) - } else if isArrayChar(ch) { - tok = EXPR - buf.WriteRune(ch) - } else if isExprsChar(ch) { - tok = EXPR - buf.WriteRune(ch) - } else if ch == ':' { - - if tok == EXPR { - buf.WriteRune(ch) - continue - } - - tbv = buf.String() - - buf.WriteRune(ch) - - if tok, lit, idv = s.part(); tok == ILLEGAL { - buf.WriteString(lit) - return ILLEGAL, buf.String(), val - } else { - buf.WriteString(lit) - } - - return THING, buf.String(), NewThing(tbv, idv) - - } else { - s.undo() - break - } - } - - // If the string matches a keyword then return that keyword. - if tok := keywords[strings.ToUpper(buf.String())]; tok > 0 { - return tok, buf.String(), val - } - - if val, err := time.ParseDuration(buf.String()); err == nil { - return DURATION, buf.String(), val - } - - // Otherwise return as a regular identifier. - return tok, buf.String(), val - -} - -// scanThing consumes the current rune and all contiguous ident runes. -func (s *scanner) scanThing(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = THING - - var tbv string - var idv interface{} - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - if tok, tbv, _ = s.part(); tok == ILLEGAL { - buf.WriteString(tbv) - return ILLEGAL, buf.String(), val - } else { - buf.WriteString(tbv) - } - - if ch := s.next(); ch == ':' { - buf.WriteRune(ch) - } else { - return ILLEGAL, buf.String(), val - } - - if tok, lit, idv = s.part(); tok == ILLEGAL { - buf.WriteString(lit) - return ILLEGAL, buf.String(), val - } else { - buf.WriteString(lit) - } - - return THING, buf.String(), NewThing(tbv, idv) - -} - -func (s *scanner) scanModel(chp ...rune) (tok Token, lit string, val interface{}) { - - var com bool - var dot bool - - var tbv string - var min float64 = 0 - var inc float64 = 0 - var max float64 = 0 - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - if tok, tbv, _ = s.part(); tok == ILLEGAL { - buf.WriteString(tbv) - return ILLEGAL, buf.String(), val - } else { - buf.WriteString(tbv) - } - - if ch := s.next(); ch == ':' { - buf.WriteRune(ch) - } else { - return ILLEGAL, buf.String(), val - } - - if ch := s.next(); isSignal(ch) { - tok, lit, _ = s.scanSignal(ch) - buf.WriteString(lit) - max, _ = strconv.ParseFloat(lit, 64) - } else { - return ILLEGAL, buf.String(), val - } - - if ch := s.next(); ch == ',' { - com = true - buf.WriteRune(ch) - if ch := s.next(); isSignal(ch) { - tok, lit, _ = s.scanSignal(ch) - buf.WriteString(lit) - inc, _ = strconv.ParseFloat(lit, 64) - } else { - return ILLEGAL, buf.String(), val - } - } else { - s.undo() - } - - if ch := s.next(); ch == '.' { - dot = true - buf.WriteRune(ch) - if ch := s.next(); ch == '.' { - buf.WriteRune(ch) - if ch := s.next(); isSignal(ch) { - tok, lit, _ = s.scanSignal(ch) - buf.WriteString(lit) - min = max - max, _ = strconv.ParseFloat(lit, 64) - } else { - return ILLEGAL, buf.String(), val - } - } else { - return ILLEGAL, buf.String(), val - } - } else { - s.undo() - } - - if ch := s.next(); ch == '|' { - buf.WriteRune(ch) - } else { - return ILLEGAL, buf.String(), val - } - - // If the minimum value is the - // same as the maximum value then - // error, as there is no ability - // to increment or decrement. - - if min == max { - return ILLEGAL, buf.String(), val - } - - // If we have a comma, but the - // value is below zero, we will - // error as this will cause an - // infinite loop in db. - - if com == true && inc <= 0 { - return ILLEGAL, buf.String(), val - } - - // If we have a min, and a max - // with .. notation, but no `inc` - // is specified, set the `inc` to - // a default of `1`. - - if dot == true && inc <= 0 { - inc = 1 - } - - // If we have a comma, but no - // max value is specified then - // error, as we need a max with - // incrementing integer ids. - - if com == true && dot == false { - return ILLEGAL, buf.String(), val - } - - return MODEL, buf.String(), NewModel(tbv, min, inc, max) - -} - -func (s *scanner) scanSignal(chp ...rune) (tok Token, lit string, val interface{}) { - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if isNumber(ch) { - buf.WriteRune(ch) - } else if ch == '.' { - if s.next() == '.' { - s.undo() - s.undo() - break - } else { - s.undo() - buf.WriteRune(ch) - } - } else { - s.undo() - break - } - } - - return NUMBER, buf.String(), nil - -} - -func (s *scanner) scanNumber(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = NUMBER - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == eof { - break - } else if isNumber(ch) { - buf.WriteRune(ch) - } else if isLetter(ch) { - if tok == NUMBER || tok == DOUBLE || tok == DURATION { - tok = IDENT - buf.WriteRune(ch) - switch ch { - case 'e', 'E': - if chn := s.next(); chn == '+' { - tok = DOUBLE - buf.WriteRune(chn) - } else if chn == '-' { - tok = DOUBLE - buf.WriteRune(chn) - } else { - s.undo() - } - case 's', 'h', 'd', 'w': - tok = DURATION - case 'n', 'u', 'µ', 'm': - tok = DURATION - if chn := s.next(); chn == eof { - break - } else if chn == 's' { - tok = DURATION - buf.WriteRune(chn) - } else if ch == 'm' { - tok = DURATION - s.undo() - } else { - s.undo() - } - } - } else { - tok = IDENT - buf.WriteRune(ch) - } - } else if ch == '.' { - if tok == DOUBLE { - tok = IDENT - } - if tok == NUMBER { - tok = DOUBLE - } - buf.WriteRune(ch) - } else { - s.undo() - break - } - } - - return tok, buf.String(), nil - -} - -func (s *scanner) scanString(chp ...rune) (tok Token, lit string, val interface{}) { - - beg := chp[0] - end := beg - - if beg == '"' { - end = '"' - } - - if beg == '`' { - end = '`' - } - - if beg == '⟨' { - end = '⟩' - } - - tok = STRING - - // Create a buffer - var buf bytes.Buffer - - // Ignore passed in runes - - // Read subsequent characters - for { - if ch := s.next(); ch == end { - break - } else if ch == eof { - return ILLEGAL, buf.String(), val - } else if ch == '\n' { - tok = REGION - buf.WriteRune(ch) - } else if ch == '\r' { - tok = REGION - buf.WriteRune(ch) - } else if ch == '\\' { - switch chn := s.next(); chn { - default: - buf.WriteRune(chn) - case 'b': - continue - case 't': - tok = REGION - buf.WriteRune('\t') - case 'r': - tok = REGION - buf.WriteRune('\r') - case 'n': - tok = REGION - buf.WriteRune('\n') - } - } else { - buf.WriteRune(ch) - } - } - - if val, err := time.Parse(RFCDate, buf.String()); err == nil { - return DATE, buf.String(), val.UTC() - } - - if val, err := time.Parse(RFCTime, buf.String()); err == nil { - return TIME, buf.String(), val.UTC() - } - - return tok, buf.String(), val - -} - -func (s *scanner) scanRegexp(chp ...rune) (tok Token, lit string, val interface{}) { - - tok = IDENT - - // Create a buffer - var buf bytes.Buffer - - // Ignore passed in runes - - // Read subsequent characters - for { - if ch := s.next(); ch == chp[0] { - break - } else if ch == eof { - return ILLEGAL, buf.String(), val - } else if ch == '\\' { - chn := s.next() - buf.WriteRune(ch) - buf.WriteRune(chn) - } else { - buf.WriteRune(ch) - } - } - - if _, err := regexp.Compile(buf.String()); err == nil { - return REGEX, buf.String(), nil - } - - return tok, buf.String(), val - -} - -func (s *scanner) scanObject(chp ...rune) (tok Token, lit string, val interface{}) { - - beg := chp[0] - end := beg - sub := 0 - qut := 0 - - if beg == '{' { - end = '}' - tok = JSON - } - - if beg == '[' { - end = ']' - tok = ARRAY - } - - // Create a buffer - var buf bytes.Buffer - - // Read passed in runes - for _, ch := range chp { - buf.WriteRune(ch) - } - - // Read subsequent characters - for { - if ch := s.next(); ch == end && sub == 0 && qut == 0 { - buf.WriteRune(ch) - break - } else if ch == beg && qut == 0 { - sub++ - buf.WriteRune(ch) - } else if ch == end && qut == 0 { - sub-- - buf.WriteRune(ch) - } else if ch == eof { - return ILLEGAL, buf.String(), val - } else if ch == '"' { - if qut == 0 { - qut++ - } else { - qut-- - } - buf.WriteRune(ch) - } else if ch == '\\' { - switch chn := s.next(); chn { - default: - return ILLEGAL, buf.String(), val - case 'b', 't', 'r', 'n', 'f', 'u', '"', '\\': - buf.WriteRune(ch) - buf.WriteRune(chn) - } - } else { - buf.WriteRune(ch) - } - } - - return tok, buf.String(), val - -} - -func (s *scanner) part() (tok Token, lit string, val interface{}) { - - if ch := s.next(); isLetter(ch) { - tok, lit, _ = s.scanIdent(ch) - } else if isNumber(ch) { - tok, lit, _ = s.scanNumber(ch) - } else if ch == '`' { - tok, lit, _ = s.scanSection(ch) - } else if ch == '⟨' { - tok, lit, _ = s.scanSection(ch) - } else { - s.undo() - tok = ILLEGAL - } - - if tok != IDENT && tok != NUMBER && tok != DOUBLE && tok != DURATION { - tok = ILLEGAL - } - - if val == nil { - val = lit - } - - return - -} - -// next reads the next rune from the bufferred reader. -// Returns the rune(0) if an error occurs (or io.EOF is returned). -func (s *scanner) next() rune { - - if len(s.a) > 0 { - var r rune - r, s.a = s.a[len(s.a)-1], s.a[:len(s.a)-1] - s.b = append(s.b, r) - return r - } - - r, _, err := s.r.ReadRune() - if err != nil { - return eof - } - s.b = append(s.b, r) - return r - -} - -// undo places the previously read rune back on the reader. -func (s *scanner) undo() { - - if len(s.b) > 0 { - var r rune - r, s.b = s.b[len(s.b)-1], s.b[:len(s.b)-1] - s.a = append(s.a, r) - return - } - - _ = s.r.UnreadRune() - -} - -// isBlank returns true if the rune is a space, tab, or newline. -func isBlank(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' -} - -// isNumber returns true if the rune is a number. -func isNumber(ch rune) bool { - return (ch >= '0' && ch <= '9') -} - -// isSignal returns true if the rune is a number. -func isSignal(ch rune) bool { - return (ch >= '0' && ch <= '9') || ch == '-' || ch == '+' -} - -// isLetter returns true if the rune is a letter. -func isLetter(ch rune) bool { - return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == 'µ' -} - -// isIdentChar returns true if the rune is allowed in a IDENT. -func isIdentChar(ch rune) bool { - return isLetter(ch) || isNumber(ch) || ch == '_' -} - -// isThingChar returns true if the rune is allowed in a THING. -func isThingChar(ch rune) bool { - return isLetter(ch) || isNumber(ch) || ch == '_' -} - -// isArrayChar returns true if the rune is allowed in an ARRAY. -func isArrayChar(ch rune) bool { - return ch == '[' || ch == ']' -} - -// isExprsChar returns true if the rune is allowed in a IDENT. -func isExprsChar(ch rune) bool { - return isLetter(ch) || isNumber(ch) || ch == '.' || ch == '_' || ch == '*' || ch == '$' -} - -// eof represents a marker rune for the end of the reader. -var eof = rune(0) diff --git a/sql/scope.go b/sql/scope.go deleted file mode 100644 index 8378ad56..00000000 --- a/sql/scope.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineScopeStatement() (stmt *DefineScopeStatement, err error) { - - stmt = &DefineScopeStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - for { - - tok, _, exi := p.mightBe(SESSION, SIGNUP, SIGNIN, CONNECT, ON) - if !exi { - break - } - - if is(tok, SESSION) { - if stmt.Time, err = p.parseDuration(); err != nil { - return nil, err - } - } - - if is(tok, SIGNUP) { - _, _, _ = p.mightBe(AS) - if stmt.Signup, err = p.parseExpr(); err != nil { - return nil, err - } - } - - if is(tok, SIGNIN) { - _, _, _ = p.mightBe(AS) - if stmt.Signin, err = p.parseExpr(); err != nil { - return nil, err - } - } - - if is(tok, CONNECT) { - _, _, _ = p.mightBe(AS) - if stmt.Connect, err = p.parseExpr(); err != nil { - return nil, err - } - } - - if is(tok, ON) { - - tok, _, err = p.shouldBe(SIGNIN, SIGNUP) - if err != nil { - return nil, err - } - - switch tok { - case SIGNUP: - if stmt.OnSignup, err = p.parseMult(); err != nil { - return nil, err - } - case SIGNIN: - if stmt.OnSignin, err = p.parseMult(); err != nil { - return nil, err - } - } - - } - - } - - return - -} - -func (p *parser) parseRemoveScopeStatement() (stmt *RemoveScopeStatement, err error) { - - stmt = &RemoveScopeStatement{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/select.go b/sql/select.go deleted file mode 100644 index dba016ac..00000000 --- a/sql/select.go +++ /dev/null @@ -1,420 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseSelectStatement() (stmt *SelectStatement, err error) { - - grw := p.buf.rw - - p.buf.rw = false - - defer func() { - p.buf.rw = grw - }() - - stmt = &SelectStatement{} - - if stmt.Expr, err = p.parseFields(); err != nil { - return nil, err - } - - _, _, err = p.shouldBe(FROM) - if err != nil { - return nil, err - } - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - if stmt.Cond, err = p.parseCond(); err != nil { - return nil, err - } - - if stmt.Split, err = p.parseSplit(); err != nil { - return nil, err - } - - if stmt.Group, err = p.parseGroup(); err != nil { - return nil, err - } - - if stmt.Order, err = p.parseOrder(); err != nil { - return nil, err - } - - if stmt.Limit, err = p.parseLimit(); err != nil { - return nil, err - } - - if stmt.Start, err = p.parseStart(); err != nil { - return nil, err - } - - if stmt.Fetch, err = p.parseFetch(); err != nil { - return nil, err - } - - if stmt.Version, err = p.parseVersion(); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - if err = checkExpression(aggrs, stmt.Expr, stmt.Group); err != nil { - return nil, err - } - - // If this query has any subqueries which - // need to alter the database then mark - // this query as a writeable statement. - - stmt.RW = p.buf.rw - - return - -} - -func (p *parser) parseFields() (mul Fields, err error) { - - for { - - one := &Field{} - - one.Expr, err = p.parseExpr() - if err != nil { - return - } - - // Chec to see if the next token is an AS - // clause, and if it is read the defined - // field alias name from the scanner. - - if _, _, exi := p.mightBe(AS); exi { - - if _, one.Alias, err = p.shouldBe(IDENT, EXPR); err != nil { - return nil, &ParseError{Found: one.Alias, Expected: []string{"alias name"}} - } - - one.Field = one.Alias - - } else { - - switch v := one.Expr.(type) { - case *Param: - one.Field = v.VA - case *Ident: - one.Field = v.VA - case *Value: - one.Field = v.VA - default: - one.Field = one.String() - } - - } - - // Append the single expression to the array - // of return statement expressions. - - mul = append(mul, one) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseSplit() (Idents, error) { - - // The next token that we expect to see is a - // SPLIT token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(SPLIT); !exi { - return nil, nil - } - - // We don't need to have a ON token, but we - // allow it so that the SQL query would read - // better when compared to english. - - _, _, _ = p.mightBe(ON) - - return p.parseIdioms() - -} - -func (p *parser) parseGroup() (mul Groups, err error) { - - // The next token that we expect to see is a - // GROUP token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(GROUP); !exi { - return nil, nil - } - - // We don't need to have a BY token, but we - // allow it so that the SQL query would read - // better when compared to english. - - _, _, _ = p.mightBe(BY) - - // If the next token is the ALL keyword then - // we will group all records together, which - // will prevent grouping by other fields. - - if _, _, exi := p.mightBe(ALL); exi { - - mul = append(mul, &Group{ - Expr: new(All), - }) - - return - - } - - // Otherwise let's parse the fields with which - // we will group the selected data, with - // multiple fields grouped by commas. - - for { - - var tok Token - var lit string - - one := &Group{} - - tok, lit, err = p.shouldBe(IDENT, EXPR) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"field name"}} - } - - one.Expr, err = p.declare(tok, lit) - if err != nil { - return nil, err - } - - // Append the single expression to the array - // of return statement expressions. - - mul = append(mul, one) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseOrder() (mul Orders, err error) { - - // The next token that we expect to see is a - // ORDER token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(ORDER); !exi { - return nil, nil - } - - // We don't need to have a BY token, but we - // allow it so that the SQL query would read - // better when compared to english. - - _, _, _ = p.mightBe(BY) - - for { - - var exi bool - var tok Token - var lit string - - one := &Order{} - - tok, lit, err = p.shouldBe(IDENT, EXPR, RAND) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"field name"}} - } - - switch tok { - default: - one.Expr, err = p.declare(tok, lit) - if err != nil { - return nil, err - } - case RAND: - one.Expr = &FuncExpression{Name: "rand"} - if _, _, exi = p.mightBe(LPAREN); exi { - _, _, err = p.shouldBe(RPAREN) - if err != nil { - return nil, err - } - } - } - - if _, _, exi = p.mightBe(COLLATE); exi { - one.Tag, err = p.parseLanguage() - if err != nil { - return nil, err - } - } - - if tok, _, exi = p.mightBe(ASC, DESC); exi { - one.Dir = (tok == ASC) - } else { - one.Dir = true - } - - // Append the single expression to the array - // of return statement expressions. - - mul = append(mul, one) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseLimit() (Expr, error) { - - // The next token that we expect to see is a - // LIMIT token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(LIMIT); !exi { - return nil, nil - } - - // We don't need to have a BY token, but we - // allow it so that the SQL query would read - // better when compared to english. - - _, _, _ = p.mightBe(BY) - - tok, lit, err := p.shouldBe(NUMBER, PARAM) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"limit number"}} - } - - return p.declare(tok, lit) - -} - -func (p *parser) parseStart() (Expr, error) { - - // The next token that we expect to see is a - // START token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(START); !exi { - return nil, nil - } - - // We don't need to have a AT token, but we - // allow it so that the SQL query would read - // better when compared to english. - - _, _, _ = p.mightBe(AT) - - tok, lit, err := p.shouldBe(NUMBER, PARAM) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"start number"}} - } - - return p.declare(tok, lit) - -} - -func (p *parser) parseFetch() (mul Fetchs, err error) { - - // The next token that we expect to see is a - // GROUP token, and if we don't find one then - // return nil, with no error. - - if _, _, exi := p.mightBe(FETCH); !exi { - return nil, nil - } - - for { - - var tok Token - var lit string - - one := &Fetch{} - - tok, lit, err = p.shouldBe(IDENT, EXPR) - if err != nil { - return nil, &ParseError{Found: lit, Expected: []string{"field name"}} - } - - one.Expr, err = p.declare(tok, lit) - if err != nil { - return nil, err - } - - // Append the single expression to the array - // of return statement expressions. - - mul = append(mul, one) - - // Check to see if the next token is a comma - // and if not, then break out of the loop, - // otherwise repeat until we find no comma. - - if _, _, exi := p.mightBe(COMMA); !exi { - break - } - - } - - return - -} - -func (p *parser) parseVersion() (Expr, error) { - - if _, _, exi := p.mightBe(VERSION, ON); !exi { - return nil, nil - } - - return p.parseExpr() - -} diff --git a/sql/sql.go b/sql/sql.go deleted file mode 100644 index ea53ebb2..00000000 --- a/sql/sql.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "time" -) - -const ( - // Parsing format for date times - RFCDate = "2006-01-02" - // Parsing format for json date times - RFCTime = time.RFC3339 - // Parsing format for json nanosecond times - RFCNano = time.RFC3339Nano -) - -var ( - allowedTypes = []string{ - "array", "boolean", - "circle", "datetime", - "number", "object", - "point", "polygon", - "record", "string", - } - - allowedAlgorithms = []string{ - "ES256", "ES384", "ES512", - "HS256", "HS384", "HS512", - "PS256", "PS384", "PS512", - "RS256", "RS384", "RS512", - } -) diff --git a/sql/sql_test.go b/sql/sql_test.go deleted file mode 100644 index e872550b..00000000 --- a/sql/sql_test.go +++ /dev/null @@ -1,3313 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "fmt" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -type tester struct { - skip bool - sql string - err string - str string - res Statement -} - -func testerr(err error) string { - if err != nil { - return err.Error() - } - return "" -} - -type Selfer interface{} - -func testsql(t *testing.T, test tester) { - - if test.skip { - Convey(" ❗️ "+test.sql, t, nil) - return - } - - s, e := Parse(test.sql) - - Convey(test.sql, t, func() { - - if test.err != "" { - Convey(testerr(e), func() { - So(testerr(e), ShouldResemble, test.err) - }) - } - - if test.err == "" { - So(e, ShouldBeNil) - So(s, ShouldResemble, test.res) - if test.str != "" { - So(fmt.Sprint(test.res.(*Query).Statements[0]), ShouldEqual, test.str) - } else { - So(fmt.Sprint(test.res.(*Query).Statements[0]), ShouldEqual, test.sql) - } - } - - }) - -} - -func TestMain(t *testing.T) { - - var tests = []tester{ - { - sql: `USE`, - err: "Found `` but expected `NAMESPACE, DATABASE, NS, DB`", - }, - { - sql: `USE NAMESPACE`, - err: "Found `` but expected `IDENT, STRING, NUMBER, DOUBLE, DATE, TIME`", - }, - { - sql: `USE NAMESPACE ''`, - err: "Found `` but expected `namespace name`", - }, - { - sql: `USE NAMESPACE name`, - res: &Query{Statements: []Statement{&UseStatement{ - NS: "name", - }}}, - }, - { - sql: `USE NAMESPACE 1`, - res: &Query{Statements: []Statement{&UseStatement{ - NS: "1", - }}}, - }, - { - sql: `USE NAMESPACE 1.3000`, - res: &Query{Statements: []Statement{&UseStatement{ - NS: "1.3000", - }}}, - }, - { - sql: `USE NAMESPACE 123.123.123.123`, - res: &Query{Statements: []Statement{&UseStatement{ - NS: "123.123.123.123", - }}}, - }, - { - sql: `USE NAMESPACE {"some":"thing"}`, - err: "Found `{\"some\":\"thing\"}` but expected `IDENT, STRING, NUMBER, DOUBLE, DATE, TIME`", - }, - { - sql: `USE NAMESPACE name something`, - err: "Found `something` but expected `;`", - }, - { - sql: `USE DATABASE`, - err: "Found `` but expected `IDENT, STRING, NUMBER, DOUBLE, DATE, TIME`", - }, - { - sql: `USE DATABASE ''`, - err: "Found `` but expected `database name`", - }, - { - sql: `USE DATABASE name`, - res: &Query{Statements: []Statement{&UseStatement{ - DB: "name", - }}}, - }, - { - sql: `USE DATABASE 1`, - res: &Query{Statements: []Statement{&UseStatement{ - DB: "1", - }}}, - }, - { - sql: `USE DATABASE 1.3000`, - res: &Query{Statements: []Statement{&UseStatement{ - DB: "1.3000", - }}}, - }, - { - sql: `USE DATABASE 123.123.123.123`, - res: &Query{Statements: []Statement{&UseStatement{ - DB: "123.123.123.123", - }}}, - }, - { - sql: `USE DATABASE {}`, - err: "Found `{}` but expected `IDENT, STRING, NUMBER, DOUBLE, DATE, TIME`", - }, - { - sql: `USE DATABASE name something`, - err: "Found `something` but expected `;`", - }, - { - sql: "USE NS `*` DB `*`", - str: "USE NAMESPACE `*` DATABASE `*`", - res: &Query{Statements: []Statement{&UseStatement{ - NS: "*", - DB: "*", - }}}, - }, - { - sql: "USE NAMESPACE `*` DATABASE `*`", - res: &Query{Statements: []Statement{&UseStatement{ - NS: "*", - DB: "*", - }}}, - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_IDs(t *testing.T) { - - Convey("All IDs should parse correctly", t, func() { - So(ParseThing("test:tester"), ShouldResemble, &Thing{ - TB: "test", - ID: string("tester"), - }) - So(ParseThing("test:123456"), ShouldResemble, &Thing{ - TB: "test", - ID: float64(123456), - }) - So(ParseThing("test:abcdef"), ShouldResemble, &Thing{ - TB: "test", - ID: string("abcdef"), - }) - So(ParseThing("test:a1b2c3"), ShouldResemble, &Thing{ - TB: "test", - ID: string("a1b2c3"), - }) - So(ParseThing("test:1a2b3c"), ShouldResemble, &Thing{ - TB: "test", - ID: string("1a2b3c"), - }) - So(ParseThing("test:4m9sms"), ShouldResemble, &Thing{ - TB: "test", - ID: string("4m9sms"), - }) - So(ParseThing("test:4m98m85ms"), ShouldResemble, &Thing{ - TB: "test", - ID: string("4m98m85ms"), - }) - So(ParseThing("test:00s5w36sm"), ShouldResemble, &Thing{ - TB: "test", - ID: string("00s5w36sm"), - }) - }) - -} - - -// Ensure the parser can parse a multi-statement query. -func Test_Parse_General(t *testing.T) { - - s := `SELECT a FROM b` - q, err := Parse(s) - - if err != nil { - t.Fatalf("unexpected error: %s", err) - } else if len(q.Statements) != 1 { - t.Fatalf("unexpected statement count: %d", len(q.Statements)) - } - -} - -// Ensure the parser can parse a multi-statement query. -func Test_Parse_General_Single(t *testing.T) { - - s := `SELECT a FROM b` - q, err := Parse(s) - - if err != nil { - t.Fatalf("unexpected error: %s", err) - } else if len(q.Statements) != 1 { - t.Fatalf("unexpected statement count: %d", len(q.Statements)) - } - -} - -// Ensure the parser can parse a multi-statement query. -func Test_Parse_General_Multi(t *testing.T) { - - s := `SELECT a FROM b; SELECT c FROM d` - q, err := Parse(s) - - if err != nil { - t.Fatalf("unexpected error: %s", err) - } else if len(q.Statements) != 2 { - t.Fatalf("unexpected statement count: %d", len(q.Statements)) - } - -} - -func Test_Parse_Queries_Malformed(t *testing.T) { - - var tests = []tester{ - { - sql: ``, - err: "Your SQL query is empty", - }, - { - sql: "SELECT ` FROM person", - err: "Found ` FROM person` but expected `expression`", - }, - { - sql: `SELECT ' FROM person`, - err: "Found ` FROM person` but expected `expression`", - }, - { - sql: `SELECT " FROM person`, - err: "Found ` FROM person` but expected `expression`", - }, - { - sql: `SELECT "\" FROM person`, - err: "Found `\" FROM person` but expected `expression`", - }, - { - sql: `!`, - err: "Found `!` but expected `USE, INFO, BEGIN, CANCEL, COMMIT, IF, LET, RETURN, LIVE, KILL, SELECT, CREATE, UPDATE, DELETE, RELATE, INSERT, UPSERT, DEFINE, REMOVE, OPTION`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Info(t *testing.T) { - - var tests = []tester{ - { - sql: `INFO`, - err: "Found `` but expected `FOR`", - }, - { - sql: `INFO FOR`, - err: "Found `` but expected `ALL, NAMESPACE, DATABASE, SCOPE, TABLE, NS, DB`", - }, - { - sql: `INFO FOR ALL`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: ALL, - }}}, - }, - { - sql: `INFO FOR NAMESPACE`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: NAMESPACE, - }}}, - }, - { - sql: `INFO FOR NS`, - str: `INFO FOR NAMESPACE`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: NS, - }}}, - }, - { - sql: `INFO FOR DATABASE`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: DATABASE, - }}}, - }, - { - sql: `INFO FOR DB`, - str: `INFO FOR DATABASE`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: DB, - }}}, - }, - { - sql: `INFO FOR SCOPE`, - err: "Found `` but expected `name`", - }, - { - sql: `INFO FOR SCOPE test`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: SCOPE, - What: &Ident{"test"}, - }}}, - }, - { - sql: `INFO FOR TABLE`, - err: "Found `` but expected `name`", - }, - { - sql: `INFO FOR TABLE test`, - res: &Query{Statements: []Statement{&InfoStatement{ - Kind: TABLE, - What: &Ident{"test"}, - }}}, - }, - { - sql: `INFO FOR TABLE test something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Let(t *testing.T) { - - var tests = []tester{ - { - sql: `LET`, - err: "Found `` but expected `name`", - }, - { - sql: `LET name`, - err: "Found `` but expected `=`", - }, - { - sql: `LET name =`, - err: "Found `=` but expected `expression`", - }, - { - sql: `LET name = true`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: true, - }}}, - }, - { - sql: `LET name = false`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: false, - }}}, - }, - { - sql: `LET name = "test"`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: &Value{"test"}, - }}}, - }, - { - sql: `LET name = 1`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: float64(1), - }}}, - }, - { - sql: `LET name = 1.0`, - str: `LET name = 1`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: float64(1), - }}}, - }, - { - sql: `LET name = 1.1`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: float64(1.1), - }}}, - }, - { - sql: `LET name = thing:test`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: &Thing{TB: "thing", ID: "test"}, - }}}, - }, - { - sql: `LET name = thing:test`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: &Thing{TB: "thing", ID: "test"}, - }}}, - }, - { - sql: `LET name = @thing:test`, - str: `LET name = thing:test`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: &Thing{TB: "thing", ID: "test"}, - }}}, - }, - { - sql: `LET name = {"key": "val"}`, - str: `LET name = {"key":"val"}`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: map[string]interface{}{"key": "val"}, - }}}, - }, - { - sql: `LET name = ["key", "val"]`, - str: `LET name = ["key","val"]`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: []interface{}{"key", "val"}, - }}}, - }, - { - sql: `LET name = $test`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: false, - Name: &Ident{"name"}, - What: &Param{"test"}, - }}}, - }, - { - sql: `LET name = (CREATE person)`, - res: &Query{Statements: []Statement{&LetStatement{ - RW: true, - Name: &Ident{"name"}, - What: &SubExpression{Expr: &CreateStatement{ - What: Exprs{&Ident{"person"}}, - Echo: AFTER, - }}, - }}}, - }, - { - sql: `LET name = "test" something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Return(t *testing.T) { - - var tests = []tester{ - { - sql: `RETURN`, - err: "Found `` but expected `expression`", - }, - { - sql: `RETURN true`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{true}, - }}}, - }, - { - sql: `RETURN true`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{true}, - }}}, - }, - { - sql: `RETURN false`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{false}, - }}}, - }, - { - sql: `RETURN "test"`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{&Value{"test"}}, - }}}, - }, - { - sql: `RETURN 1`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{float64(1)}, - }}}, - }, - { - sql: `RETURN 1.0`, - str: `RETURN 1`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{float64(1)}, - }}}, - }, - { - sql: `RETURN 1.1`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{float64(1.1)}, - }}}, - }, - { - sql: `RETURN @thing:test`, - str: `RETURN thing:test`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{&Thing{TB: "thing", ID: "test"}}, - }}}, - }, - { - sql: `RETURN {"key": "val"}`, - str: `RETURN {"key":"val"}`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{map[string]interface{}{"key": "val"}}, - }}}, - }, - { - sql: `RETURN ["key", "val"]`, - str: `RETURN ["key","val"]`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{[]interface{}{"key", "val"}}, - }}}, - }, - { - sql: `RETURN $test`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: false, - What: Exprs{&Param{"test"}}, - }}}, - }, - { - sql: `RETURN (CREATE person)`, - res: &Query{Statements: []Statement{&ReturnStatement{ - RW: true, - What: Exprs{&SubExpression{Expr: &CreateStatement{ - What: Exprs{&Ident{"person"}}, - Echo: AFTER, - }}}, - }}}, - }, - { - sql: `RETURN $test something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Select(t *testing.T) { - - date, _ := time.Parse("2006-01-02", "1987-06-22") - nano, _ := time.Parse(time.RFC3339, "1987-06-22T08:30:30.511Z") - - var tests = []tester{ - { - sql: `SELECT`, - err: "Found `` but expected `expression`", - }, - { - sql: `SELECT FROM`, - err: "Found `FROM` but expected `expression`", - }, - { - sql: `SELECT *`, - err: "Found `` but expected `FROM`", - }, - { - sql: `SELECT * FROM`, - err: "Found `` but expected `expression`", - }, - { - sql: `SELECT * FROM per!son`, - err: "Found `!` but expected `;`", - }, - { - sql: `SELECT * FROM person`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - }}}, - }, - { - sql: `SELECT * FROM @`, - err: "Found `@` but expected `expression`", - }, - { - sql: `SELECT * FROM @person`, - err: "Found `@person` but expected `expression`", - }, - { - sql: `SELECT * FROM @person:`, - err: "Found `@person:` but expected `expression`", - }, - { - sql: `SELECT * FROM @person WHERE`, - err: "Found `@person` but expected `expression`", - }, - { - sql: "SELECT * FROM 111", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{float64(111)}, - }}}, - }, - { - sql: "SELECT * FROM `111`", - str: "SELECT * FROM 111", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"111"}}, - }}}, - }, - { - sql: "SELECT * FROM `2006-01-02`", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"2006-01-02"}}, - }}}, - }, - { - sql: "SELECT * FROM `2006-01-02T15:04:05+07:00`", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"2006-01-02T15:04:05+07:00"}}, - }}}, - }, - { - sql: "SELECT * FROM `2006-01-02T15:04:05.999999999+07:00`", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"2006-01-02T15:04:05.999999999+07:00"}}, - }}}, - }, - { - sql: `SELECT * FROM person`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - }}}, - }, - { - sql: `SELECT * FROM person, tweet`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}, &Ident{"tweet"}}, - }}}, - }, - { - sql: `SELECT * FROM person:1a`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "1a"}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨1a⟩`, - str: `SELECT * FROM person:1a`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "1a"}}, - }}}, - }, - { - sql: `SELECT * FROM person:123456`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: float64(123456)}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨123456⟩`, - str: `SELECT * FROM person:123456`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: float64(123456)}}, - }}}, - }, - { - sql: `SELECT * FROM person:123.456`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: float64(123.456)}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨123.456⟩`, - str: `SELECT * FROM person:123.456`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: float64(123.456)}}, - }}}, - }, - { - sql: `SELECT * FROM person:123.456.789.012`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "123.456.789.012"}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨123.456.789.012⟩`, - str: `SELECT * FROM person:123.456.789.012`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "123.456.789.012"}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨1987-06-22⟩`, - str: `SELECT * FROM person:⟨1987-06-22T00:00:00Z⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: date}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨1987-06-22T08:30:30.511Z⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: nano}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨A250C5A3-948F-4657-88AD-FF5F27B5B24E⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "A250C5A3-948F-4657-88AD-FF5F27B5B24E"}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨8250C5A3-948F-4657-88AD-FF5F27B5B24E⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "8250C5A3-948F-4657-88AD-FF5F27B5B24E"}}, - }}}, - }, - { - sql: `SELECT * FROM person:⟨Tobie Morgan Hitchcock⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "person", ID: "Tobie Morgan Hitchcock"}}, - }}}, - }, - { - sql: `SELECT * FROM ⟨email addresses⟩:⟨tobie@abcum.com⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "email addresses", ID: "tobie@abcum.com"}}, - }}}, - }, - { - sql: `SELECT * FROM ⟨email addresses⟩:⟨tobie+spam@abcum.com⟩`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Thing{TB: "email addresses", ID: "tobie+spam@abcum.com"}}, - }}}, - }, - { - sql: `SELECT *, temp AS test FROM person`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{ - {Expr: &All{}, Field: "*"}, - {Expr: &Ident{"temp"}, Field: "test", Alias: "test"}, - }, - What: []Expr{&Ident{"person"}}, - }}}, - }, - { - sql: "SELECT `email addresses` AS emails FROM person", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{ - {Expr: &Ident{"email addresses"}, Field: "emails", Alias: "emails"}, - }, - What: []Expr{&Ident{"person"}}, - }}}, - }, - { - sql: "SELECT emails AS `email addresses` FROM person", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{ - {Expr: &Ident{"emails"}, Field: "email addresses", Alias: "email addresses"}, - }, - What: []Expr{&Ident{"person"}}, - }}}, - }, - { - sql: `SELECT * FROM (CREATE person)`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: true, - Expr: []*Field{ - {Expr: &All{}, Field: "*"}, - }, - What: Exprs{&SubExpression{Expr: &CreateStatement{ - What: Exprs{&Ident{"person"}}, - Echo: AFTER, - }}}, - }}}, - }, - { - sql: "SELECT * FROM person WHERE id = \"\x0A\"", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"id"}, Op: EQ, RHS: &Value{"\n"}}, - }}}, - }, - { - sql: "SELECT * FROM person WHERE id = \"\x0D\"", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"id"}, Op: EQ, RHS: &Value{"\r"}}, - }}}, - }, - { - sql: "SELECT * FROM person WHERE id = \"\b\n\r\t\"", - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"id"}, Op: EQ, RHS: &Value{"\b\n\r\t"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE`, - err: "Found `` but expected `expression`", - }, - { - sql: `SELECT * FROM person WHERE id`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &Ident{"id"}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE id = `, - err: "Found `` but expected `expression`", - }, - { - sql: `SELECT * FROM person WHERE id = 1`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"id"}, Op: EQ, RHS: float64(1)}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old = EMPTY`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: EQ, RHS: &Empty{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old != EMPTY`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: NEQ, RHS: &Empty{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old = MISSING`, - str: `SELECT * FROM person WHERE old = VOID`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: EQ, RHS: &Void{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old != MISSING`, - str: `SELECT * FROM person WHERE old != VOID`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: NEQ, RHS: &Void{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old IS EMPTY`, - str: `SELECT * FROM person WHERE old = EMPTY`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: EQ, RHS: &Empty{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old IS NOT EMPTY`, - str: `SELECT * FROM person WHERE old != EMPTY`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: NEQ, RHS: &Empty{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old IS MISSING`, - str: `SELECT * FROM person WHERE old = VOID`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: EQ, RHS: &Void{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old IS NOT MISSING`, - str: `SELECT * FROM person WHERE old != VOID`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: NEQ, RHS: &Void{}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old = true`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: EQ, RHS: true}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE old = false`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"old"}, Op: EQ, RHS: false}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE id != NULL AND id > 13.9 AND id < 31 AND id >= 15 AND id <= 29.9`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &Ident{"id"}, - Op: NEQ, - RHS: &Null{}, - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &Ident{"id"}, - Op: GT, - RHS: float64(13.9), - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &Ident{"id"}, - Op: LT, - RHS: float64(31), - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &Ident{"id"}, - Op: GTE, - RHS: float64(15), - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &Ident{"id"}, - Op: LTE, - RHS: float64(29.9), - }, - }, - }, - }, - }, - }}}, - }, - { - sql: `SELECT * FROM person WHERE 2 * 3 + 4 = 10`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: float64(2), - Op: MUL, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: ADD, - RHS: float64(4), - }, - }, - Op: EQ, - RHS: float64(10), - }, - }}}, - }, - { - sql: `SELECT * FROM person WHERE 2 + 3 * 4 = 14`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: float64(2), - Op: ADD, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: MUL, - RHS: float64(4), - }, - }, - Op: EQ, - RHS: float64(14), - }, - }}}, - }, - { - sql: `SELECT * FROM person WHERE 2 * 3 + 3 * 4 = 18`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: float64(2), - Op: MUL, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: ADD, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: MUL, - RHS: float64(4), - }, - }, - }, - Op: EQ, - RHS: float64(18), - }, - }}}, - }, - { - sql: `SELECT * FROM person WHERE 2 + 3 + 3 * 4 = 17`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: float64(2), - Op: ADD, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: ADD, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: MUL, - RHS: float64(4), - }, - }, - }, - Op: EQ, - RHS: float64(17), - }, - }}}, - }, - { - sql: `SELECT * FROM person WHERE (2 + 3 + 3) * 4 = 32`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &SubExpression{ - Expr: &BinaryExpression{ - LHS: float64(2), - Op: ADD, - RHS: &BinaryExpression{ - LHS: float64(3), - Op: ADD, - RHS: float64(3), - }, - }, - }, - Op: MUL, - RHS: float64(4), - }, - Op: EQ, - RHS: float64(32), - }, - }}}, - }, - { - sql: `SELECT * FROM person WHERE test IN ["London","Paris"]`, - str: `SELECT * FROM person WHERE test ∈ ["London","Paris"]`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"test"}, Op: INS, RHS: []interface{}{"London", "Paris"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE test IS IN ["London","Paris"]`, - str: `SELECT * FROM person WHERE test ∈ ["London","Paris"]`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"test"}, Op: INS, RHS: []interface{}{"London", "Paris"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE test IS NOT IN ["London","Paris"]`, - str: `SELECT * FROM person WHERE test ∉ ["London","Paris"]`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"test"}, Op: NIS, RHS: []interface{}{"London", "Paris"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE ["London","Paris"] CONTAINS test`, - str: `SELECT * FROM person WHERE ["London","Paris"] ∋ test`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: []interface{}{"London", "Paris"}, Op: SIN, RHS: &Ident{"test"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE ["London","Paris"] CONTAINS NOT test`, - str: `SELECT * FROM person WHERE ["London","Paris"] ∌ test`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: []interface{}{"London", "Paris"}, Op: SNI, RHS: &Ident{"test"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE test = {`, - err: "Found `{` but expected `expression`", - }, - { - sql: `SELECT * FROM person WHERE test = {"name":"London"}`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"test"}, Op: EQ, RHS: map[string]interface{}{"name": "London"}}, - }}}, - }, - { - sql: `SELECT * FROM person WHERE test = {"name":{"f":"first","l":"last"}}`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{LHS: &Ident{"test"}, Op: EQ, RHS: map[string]interface{}{"name": map[string]interface{}{"f": "first", "l": "last"}}}, - }}}, - }, - { - sql: `SELECT * FROM person TIMEOUT 1s`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `SELECT * FROM person TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - } - - /*bday1, _ := time.Parse("2006-01-02", "1987-06-22") - bday2, _ := time.Parse(time.RFC3339, "1987-06-22T08:00:00Z") - bday3, _ := time.Parse(time.RFC3339, "1987-06-22T08:30:00.193943735Z") - bday4, _ := time.Parse(time.RFC3339, "2016-03-14T11:19:31.193943735Z") - - tests = append(tests, tester{ - sql: `SELECT * FROM person WHERE bday >= "1987-06-22" AND bday >= "1987-06-22T08:00:00Z" AND bday >= "1987-06-22T08:30:00.193943735Z" AND bday <= "2016-03-14T11:19:31.193943735Z"`, - res: &Query{Statements: []Statement{&SelectStatement{ - RW: true, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &Ident{"bday"}, - Op: GTE, - RHS: bday1, - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &Ident{"bday"}, - Op: GTE, - RHS: bday2, - }, - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &Ident{"bday"}, - Op: GTE, - RHS: bday3, - }, - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &Ident{"bday"}, - Op: LTE, - RHS: bday4, - }, - }, - }}}, - })*/ - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Create(t *testing.T) { - - var tests = []tester{ - { - sql: `CREATE`, - err: "Found `` but expected `expression`", - }, - { - sql: `CREATE person`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person SET 123`, - err: "Found `123` but expected `field name`", - }, - { - sql: `CREATE person SET firstname`, - err: "Found `` but expected `=, +=, -=`", - }, - { - sql: `CREATE person SET firstname = VOID`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"firstname"}, Op: EQ, RHS: &Void{}}}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person SET firstname = EMPTY`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"firstname"}, Op: EQ, RHS: &Empty{}}}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person SET firstname = "Tobie" something`, - err: "Found `something` but expected `;`", - }, - { - sql: `CREATE person SET firstname = "Tobie"`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"firstname"}, Op: EQ, RHS: &Value{"Tobie"}}}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person MERGE something`, - err: "Found `something` but expected `json`", - }, - { - sql: `CREATE person MERGE {"firstname"::"Tobie"}`, - err: "Found `{\"firstname\"::\"Tobie\"}` but expected `json`", - }, - { - sql: `CREATE person MERGE {"firstname":"Tobie"} something`, - err: "Found `something` but expected `;`", - }, - { - sql: `CREATE person MERGE {"firstname":"Tobie"}`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &MergeExpression{Data: map[string]interface{}{"firstname": "Tobie"}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person CONTENT {"test":"{{{"}`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &ContentExpression{Data: map[string]interface{}{"test": "{{{"}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person CONTENT something`, - err: "Found `something` but expected `json`", - }, - { - sql: `CREATE person CONTENT {"firstname"::"Tobie"}`, - err: "Found `{\"firstname\"::\"Tobie\"}` but expected `json`", - }, - { - sql: `CREATE person CONTENT {"firstname":"Tobie"} something`, - err: "Found `something` but expected `;`", - }, - { - sql: `CREATE person CONTENT {"firstname":"Tobie"}`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &ContentExpression{Data: map[string]interface{}{"firstname": "Tobie"}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person RETURN`, - err: "Found `` but expected `NONE, BEFORE, AFTER`", - }, - { - sql: `CREATE person RETURN NONE`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: NONE, - }}}, - }, - { - sql: `CREATE person RETURN BEFORE`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: BEFORE, - }}}, - }, - { - sql: `CREATE person RETURN AFTER`, - str: `CREATE person`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - }}}, - }, - { - sql: `CREATE person TIMEOUT 1s`, - res: &Query{Statements: []Statement{&CreateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `CREATE person TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `CREATE person something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Update(t *testing.T) { - - var tests = []tester{ - { - sql: `UPDATE`, - err: "Found `` but expected `expression`", - }, - { - sql: `UPDATE person`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person SET 123`, - err: "Found `123` but expected `field name`", - }, - { - sql: `UPDATE person SET firstname`, - err: "Found `` but expected `=, +=, -=`", - }, - { - sql: `UPDATE person SET firstname = VOID`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"firstname"}, Op: EQ, RHS: &Void{}}}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person SET firstname = EMPTY`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"firstname"}, Op: EQ, RHS: &Empty{}}}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person SET firstname = "Tobie" something`, - err: "Found `something` but expected `;`", - }, - { - sql: `UPDATE person SET firstname = "Tobie"`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"firstname"}, Op: EQ, RHS: &Value{"Tobie"}}}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person DIFF something`, - err: "Found `something` but expected `json`", - }, - { - sql: `UPDATE person DIFF {} something`, - err: "Found `{}` but expected `json`", - }, - { - sql: `UPDATE person DIFF [] something`, - err: "Found `something` but expected `;`", - }, - { - sql: `UPDATE person DIFF []`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &DiffExpression{Data: []interface{}{}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person MERGE something`, - err: "Found `something` but expected `json`", - }, - { - sql: `UPDATE person MERGE {"firstname"::"Tobie"}`, - err: "Found `{\"firstname\"::\"Tobie\"}` but expected `json`", - }, - { - sql: `UPDATE person MERGE {"firstname":"Tobie"} something`, - err: "Found `something` but expected `;`", - }, - { - sql: `UPDATE person MERGE {"firstname":"Tobie"}`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &MergeExpression{Data: map[string]interface{}{"firstname": "Tobie"}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person CONTENT something`, - err: "Found `something` but expected `json`", - }, - { - sql: `UPDATE person CONTENT {"firstname"::"Tobie"}`, - err: "Found `{\"firstname\"::\"Tobie\"}` but expected `json`", - }, - { - sql: `UPDATE person CONTENT {"firstname":"Tobie"} something`, - err: "Found `something` but expected `;`", - }, - { - sql: `UPDATE person CONTENT {"firstname":"Tobie"}`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &ContentExpression{Data: map[string]interface{}{"firstname": "Tobie"}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person CONTENT {"test":"{{{"}`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Data: &ContentExpression{Data: map[string]interface{}{"test": "{{{"}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person RETURN`, - err: "Found `` but expected `NONE, BEFORE, AFTER`", - }, - { - sql: `UPDATE person RETURN NONE`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: NONE, - }}}, - }, - { - sql: `UPDATE person RETURN BEFORE`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: BEFORE, - }}}, - }, - { - sql: `UPDATE person RETURN AFTER`, - str: `UPDATE person`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - }}}, - }, - { - sql: `UPDATE person TIMEOUT 1s`, - res: &Query{Statements: []Statement{&UpdateStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `UPDATE person TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `UPDATE person something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Delete(t *testing.T) { - - var tests = []tester{ - { - sql: `DELETE`, - err: "Found `` but expected `expression`", - }, - { - sql: `DELETE FROM`, - err: "Found `` but expected `expression`", - }, - { - sql: `DELETE person`, - res: &Query{Statements: []Statement{&DeleteStatement{ - What: []Expr{&Ident{"person"}}, - Echo: NONE, - }}}, - }, - { - sql: `DELETE person RETURN`, - err: "Found `` but expected `NONE, BEFORE, AFTER`", - }, - { - sql: `DELETE person RETURN NONE`, - str: `DELETE person`, - res: &Query{Statements: []Statement{&DeleteStatement{ - What: []Expr{&Ident{"person"}}, - Echo: NONE, - }}}, - }, - { - sql: `DELETE person RETURN BEFORE`, - res: &Query{Statements: []Statement{&DeleteStatement{ - What: []Expr{&Ident{"person"}}, - Echo: BEFORE, - }}}, - }, - { - sql: `DELETE person RETURN AFTER`, - res: &Query{Statements: []Statement{&DeleteStatement{ - What: []Expr{&Ident{"person"}}, - Echo: AFTER, - }}}, - }, - { - sql: `DELETE person TIMEOUT 1s`, - res: &Query{Statements: []Statement{&DeleteStatement{ - What: []Expr{&Ident{"person"}}, - Echo: NONE, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `DELETE person TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `DELETE person something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Relate(t *testing.T) { - - var tests = []tester{ - { - sql: `RELATE`, - err: "Found `` but expected `expression`", - }, - { - sql: `RELATE person`, - err: "Found `` but expected `->, <-`", - }, - { - sql: `RELATE person ->`, - err: "Found `` but expected `table`", - }, - { - sql: `RELATE person -> purchase`, - err: "Found `` but expected `->`", - }, - { - sql: `RELATE item <- purchase`, - err: "Found `` but expected `<-`", - }, - { - sql: `RELATE person -> purchase -> `, - err: "Found `` but expected `expression`", - }, - { - sql: `RELATE item <- purchase <- `, - err: "Found `` but expected `expression`", - }, - { - sql: `RELATE person -> purchase -> item`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Echo: AFTER, - }}}, - }, - { - sql: `RELATE item <- purchase <- person`, - str: `RELATE person -> purchase -> item`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Echo: AFTER, - }}}, - }, - { - sql: `RELATE person -> purchase -> item UNIQUE`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Uniq: true, - Echo: AFTER, - }}}, - }, - { - sql: `RELATE item <- purchase <- person UNIQUE`, - str: `RELATE person -> purchase -> item UNIQUE`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Uniq: true, - Echo: AFTER, - }}}, - }, - { - sql: `RELATE person -> purchase -> item SET 123`, - err: "Found `123` but expected `field name`", - }, - { - sql: `RELATE person -> purchase -> item SET firstname`, - err: "Found `` but expected `=, +=, -=`", - }, - { - sql: `RELATE person -> purchase -> item SET public = true`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Data: &DataExpression{Data: []*ItemExpression{{LHS: &Ident{"public"}, Op: EQ, RHS: true}}}, - Echo: AFTER, - }}}, - }, - { - sql: `RELATE person -> purchase -> item RETURN`, - err: "Found `` but expected `NONE, BEFORE, AFTER`", - }, - { - sql: `RELATE person -> purchase -> item RETURN NONE`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Echo: NONE, - }}}, - }, - { - sql: `RELATE person -> purchase -> item RETURN BEFORE`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Echo: BEFORE, - }}}, - }, - { - sql: `RELATE person -> purchase -> item RETURN AFTER`, - str: `RELATE person -> purchase -> item`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Echo: AFTER, - }}}, - }, - { - sql: `RELATE person -> purchase -> item TIMEOUT 1s`, - res: &Query{Statements: []Statement{&RelateStatement{ - Type: &Table{"purchase"}, - From: []Expr{&Ident{"person"}}, - With: []Expr{&Ident{"item"}}, - Echo: AFTER, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `RELATE person -> purchase -> item TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `RELATE person -> purchase -> item something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Insert(t *testing.T) { - - var tests = []tester{ - { - sql: `INSERT`, - err: "Found `` but expected `expression`", - }, - { - sql: `INSERT ["one","two","tre"]`, - err: "Found `` but expected `INTO`", - }, - { - sql: `INSERT ["one","two","tre"] INTO`, - err: "Found `` but expected `table`", - }, - { - sql: `INSERT ["one","two","tre"] INTO person`, - res: &Query{Statements: []Statement{&InsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: AFTER, - }}}, - }, - { - sql: `INSERT ["one","two","tre"] INTO person RETURN`, - err: "Found `` but expected `NONE, BEFORE, AFTER`", - }, - { - sql: `INSERT ["one","two","tre"] INTO person RETURN NONE`, - res: &Query{Statements: []Statement{&InsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: NONE, - }}}, - }, - { - sql: `INSERT ["one","two","tre"] INTO person RETURN BEFORE`, - res: &Query{Statements: []Statement{&InsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: BEFORE, - }}}, - }, - { - sql: `INSERT ["one","two","tre"] INTO person RETURN AFTER`, - str: `INSERT ["one","two","tre"] INTO person`, - res: &Query{Statements: []Statement{&InsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: AFTER, - }}}, - }, - { - sql: `INSERT ["one","two","tre"] INTO person TIMEOUT 1s`, - res: &Query{Statements: []Statement{&InsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: AFTER, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `INSERT ["one","two","tre"] INTO person TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `INSERT ["one","two","tre"] INTO person something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Upsert(t *testing.T) { - - var tests = []tester{ - { - sql: `UPSERT`, - err: "Found `` but expected `expression`", - }, - { - sql: `UPSERT ["one","two","tre"]`, - err: "Found `` but expected `INTO`", - }, - { - sql: `UPSERT ["one","two","tre"] INTO`, - err: "Found `` but expected `table`", - }, - { - sql: `UPSERT ["one","two","tre"] INTO person`, - res: &Query{Statements: []Statement{&UpsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: AFTER, - }}}, - }, - { - sql: `UPSERT ["one","two","tre"] INTO person RETURN`, - err: "Found `` but expected `NONE, BEFORE, AFTER`", - }, - { - sql: `UPSERT ["one","two","tre"] INTO person RETURN NONE`, - res: &Query{Statements: []Statement{&UpsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: NONE, - }}}, - }, - { - sql: `UPSERT ["one","two","tre"] INTO person RETURN BEFORE`, - res: &Query{Statements: []Statement{&UpsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: BEFORE, - }}}, - }, - { - sql: `UPSERT ["one","two","tre"] INTO person RETURN AFTER`, - str: `UPSERT ["one","two","tre"] INTO person`, - res: &Query{Statements: []Statement{&UpsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: AFTER, - }}}, - }, - { - sql: `UPSERT ["one","two","tre"] INTO person TIMEOUT 1s`, - res: &Query{Statements: []Statement{&UpsertStatement{ - Data: []interface{}{"one", "two", "tre"}, - Into: &Table{"person"}, - Echo: AFTER, - Timeout: 1 * time.Second, - }}}, - }, - { - sql: `UPSERT ["one","two","tre"] INTO person TIMEOUT null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `UPSERT ["one","two","tre"] INTO person something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Live(t *testing.T) { - - var tests = []tester{ - { - sql: `LIVE`, - err: "Found `` but expected `SELECT`", - }, - { - sql: `LIVE SELECT`, - err: "Found `` but expected `expression`", - }, - { - sql: `LIVE SELECT *`, - err: "Found `` but expected `FROM`", - }, - { - sql: `LIVE SELECT * FROM`, - err: "Found `` but expected `expression`", - }, - { - sql: `LIVE SELECT * FROM person`, - res: &Query{Statements: []Statement{&LiveStatement{ - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: Exprs{&Ident{"person"}}, - }}}, - }, - { - sql: `LIVE SELECT * FROM person WHERE`, - err: "Found `` but expected `expression`", - }, - { - sql: `LIVE SELECT * FROM person WHERE public = true`, - res: &Query{Statements: []Statement{&LiveStatement{ - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: Exprs{&Ident{"person"}}, - Cond: &BinaryExpression{ - LHS: &Ident{"public"}, - Op: EQ, - RHS: true, - }, - }}}, - }, - { - sql: `LIVE SELECT * FROM person WHERE public = true something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Kill(t *testing.T) { - - var tests = []tester{ - { - sql: `KILL`, - err: "Found `` but expected `expression`", - }, - { - sql: `KILL identifier`, - res: &Query{Statements: []Statement{&KillStatement{ - What: Exprs{&Ident{"identifier"}}, - }}}, - }, - { - sql: `KILL "identifier"`, - res: &Query{Statements: []Statement{&KillStatement{ - What: Exprs{&Value{"identifier"}}, - }}}, - }, - { - sql: `KILL "identifier" something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Define(t *testing.T) { - - var tests = []tester{ - { - sql: `DEFINE`, - err: "Found `` but expected `NAMESPACE, DATABASE, LOGIN, TOKEN, SCOPE, TABLE, EVENT, FIELD, INDEX`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE NAMESPACE`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE NAMESPACE 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `DEFINE NAMESPACE 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `DEFINE NAMESPACE test`, - res: &Query{Statements: []Statement{&DefineNamespaceStatement{ - Name: &Ident{"test"}, - }}}, - }, - { - sql: `DEFINE NAMESPACE test something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE DATABASE`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE DATABASE 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `DEFINE DATABASE 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `DEFINE DATABASE test`, - res: &Query{Statements: []Statement{&DefineDatabaseStatement{ - Name: &Ident{"test"}, - }}}, - }, - { - sql: `DEFINE DATABASE test something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE LOGIN`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE LOGIN 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `DEFINE LOGIN 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `DEFINE LOGIN test`, - err: "Found `` but expected `ON`", - }, - { - sql: `DEFINE LOGIN test ON`, - err: "Found `` but expected `NAMESPACE, DATABASE`", - }, - { - sql: `DEFINE LOGIN test ON something`, - err: "Found `something` but expected `NAMESPACE, DATABASE`", - }, - { - sql: `DEFINE LOGIN test ON NAMESPACE`, - err: "Found `` but expected `PASSWORD, PASSHASH`", - }, - { - sql: `DEFINE LOGIN test ON NAMESPACE PASSWORD`, - err: "Found `` but expected `string`", - }, - { - sql: `DEFINE LOGIN test ON NAMESPACE PASSWORD "123456"`, - str: `DEFINE LOGIN test ON NAMESPACE PASSHASH "123456"`, - res: &Query{Statements: []Statement{&DefineLoginStatement{ - Kind: NAMESPACE, - User: &Ident{"test"}, - Pass: []byte("123456"), - }}}, - }, - { - sql: `DEFINE LOGIN test ON DATABASE PASSWORD "123456"`, - str: `DEFINE LOGIN test ON DATABASE PASSHASH "123456"`, - res: &Query{Statements: []Statement{&DefineLoginStatement{ - Kind: DATABASE, - User: &Ident{"test"}, - Pass: []byte("123456"), - }}}, - }, - { - sql: `DEFINE LOGIN test ON NAMESPACE PASSWORD "123456" something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE TOKEN`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE TOKEN 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `DEFINE TOKEN 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `DEFINE TOKEN test`, - err: "Found `` but expected `ON`", - }, - { - sql: `DEFINE TOKEN test ON`, - err: "Found `` but expected `NAMESPACE, DATABASE, SCOPE`", - }, - { - sql: `DEFINE TOKEN test ON something`, - err: "Found `something` but expected `NAMESPACE, DATABASE, SCOPE`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE`, - err: "Found `` but expected `TYPE`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE TYPE 100`, - err: "Found `100` but expected `ES256, ES384, ES512, HS256, HS384, HS512, PS256, PS384, PS512, RS256, RS384, RS512`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE TYPE XX512`, - err: "Found `XX512` but expected `ES256, ES384, ES512, HS256, HS384, HS512, PS256, PS384, PS512, RS256, RS384, RS512`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE TYPE HS512`, - err: "Found `` but expected `VALUE`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE TYPE HS512`, - err: "Found `` but expected `VALUE`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE TYPE HS512 VALUE`, - err: "Found `` but expected `string`", - }, - { - sql: `DEFINE TOKEN test ON NAMESPACE TYPE HS512 VALUE "secret"`, - str: `DEFINE TOKEN test ON NAMESPACE TYPE HS512 VALUE "secret"`, - res: &Query{Statements: []Statement{&DefineTokenStatement{ - Kind: NAMESPACE, - Name: &Ident{"test"}, - What: &Ident{""}, - Type: "HS512", - Code: []byte("secret"), - }}}, - }, - { - sql: `DEFINE TOKEN test ON DATABASE TYPE HS512 VALUE "secret"`, - str: `DEFINE TOKEN test ON DATABASE TYPE HS512 VALUE "secret"`, - res: &Query{Statements: []Statement{&DefineTokenStatement{ - Kind: DATABASE, - Name: &Ident{"test"}, - What: &Ident{""}, - Type: "HS512", - Code: []byte("secret"), - }}}, - }, - { - sql: `DEFINE TOKEN test ON SCOPE test TYPE HS512 VALUE "secret"`, - str: `DEFINE TOKEN test ON SCOPE test TYPE HS512 VALUE "secret"`, - res: &Query{Statements: []Statement{&DefineTokenStatement{ - Kind: SCOPE, - Name: &Ident{"test"}, - What: &Ident{"test"}, - Type: "HS512", - Code: []byte("secret"), - }}}, - }, - { - sql: `DEFINE TOKEN test ON SCOPE test TYPE HS512 VALUE "secret" something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE SCOPE`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE SCOPE 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `DEFINE SCOPE 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `DEFINE SCOPE test`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - }}}, - }, - { - sql: `DEFINE SCOPE test SESSION null`, - err: "Found `null` but expected `duration`", - }, - { - sql: `DEFINE SCOPE test SESSION 1h`, - str: `DEFINE SCOPE test SESSION 1h0m0s`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Time: 1 * time.Hour, - }}}, - }, - { - sql: `DEFINE SCOPE test SESSION 1d`, - str: `DEFINE SCOPE test SESSION 24h0m0s`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Time: 24 * time.Hour, - }}}, - }, - { - sql: `DEFINE SCOPE test SESSION 1w`, - str: `DEFINE SCOPE test SESSION 168h0m0s`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Time: 168 * time.Hour, - }}}, - }, - { - sql: `DEFINE SCOPE test SIGNUP AS NONE`, - err: "Found `NONE` but expected `expression`", - }, - { - sql: `DEFINE SCOPE test SIGNUP AS (CREATE person)`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Signup: &SubExpression{ - Expr: &CreateStatement{ - What: Exprs{&Ident{"person"}}, - Echo: AFTER, - }, - }, - }}}, - }, - { - sql: `DEFINE SCOPE test SIGNIN AS NONE`, - err: "Found `NONE` but expected `expression`", - }, - { - sql: `DEFINE SCOPE test SIGNIN AS (SELECT * FROM person)`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Signin: &SubExpression{ - Expr: &SelectStatement{ - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"person"}}, - }, - }, - }}}, - }, - { - sql: `DEFINE SCOPE test CONNECT AS NONE`, - err: "Found `NONE` but expected `expression`", - }, - { - sql: `DEFINE SCOPE test CONNECT AS (SELECT * FROM $id)`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Connect: &SubExpression{ - Expr: &SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Param{"id"}}, - }, - }, - }}}, - }, - { - sql: `DEFINE SCOPE test SIGNUP AS (CREATE tester) SIGNIN AS (SELECT * FROM tester) CONNECT AS (SELECT * FROM $id)`, - res: &Query{Statements: []Statement{&DefineScopeStatement{ - Name: &Ident{"test"}, - Signup: &SubExpression{ - Expr: &CreateStatement{ - What: []Expr{&Ident{"tester"}}, - Echo: AFTER, - }, - }, - Signin: &SubExpression{ - Expr: &SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Ident{"tester"}}, - }, - }, - Connect: &SubExpression{ - Expr: &SelectStatement{ - RW: false, - Expr: []*Field{{Expr: &All{}, Field: "*"}}, - What: []Expr{&Param{"id"}}, - }, - }, - }}}, - }, - { - sql: `DEFINE SCOPE test something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE TABLE`, - err: "Found `` but expected `table`", - }, - { - sql: `DEFINE TABLE 111`, - err: "Found `111` but expected `table`", - }, - { - sql: `DEFINE TABLE 111.111`, - err: "Found `111.111` but expected `table`", - }, - { - sql: `DEFINE TABLE person`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - }}}, - }, - { - sql: `DEFINE TABLE person something`, - err: "Found `something` but expected `;`", - }, - { - sql: `DEFINE TABLE person DROP`, - str: `DEFINE TABLE person DROP`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Drop: true, - }}}, - }, - { - sql: `DEFINE TABLE person SCHEMALESS`, - str: `DEFINE TABLE person`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Full: false, - }}}, - }, - { - sql: `DEFINE TABLE person SCHEMAFULL`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Full: true, - }}}, - }, - { - sql: `DEFINE TABLE person PERMISSIONS SOME`, - err: "Found `SOME` but expected `FOR, NONE, FULL, WHERE`", - }, - { - sql: `DEFINE TABLE person PERMISSIONS NONE`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: false, - Create: false, - Update: false, - Delete: false, - }, - }}}, - }, - { - sql: `DEFINE TABLE person PERMISSIONS FULL`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: true, - Create: true, - Update: true, - Delete: true, - }, - }}}, - }, - { - sql: `DEFINE TABLE person PERMISSIONS WHERE public = true`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Create: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Update: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Delete: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - }, - }}}, - }, - { - sql: `DEFINE TABLE person PERMISSIONS FOR select FULL FOR insert, upsert NONE`, - err: "Found `insert` but expected `SELECT, CREATE, UPDATE, DELETE`", - }, - { - sql: `DEFINE TABLE person PERMISSIONS FOR select FULL FOR create, update, delete SOME`, - err: "Found `SOME` but expected `FULL, NONE, WHERE`", - }, - { - sql: `DEFINE TABLE person PERMISSIONS FOR select FULL FOR create, update, delete NONE`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: true, - Create: false, - Update: false, - Delete: false, - }, - }}}, - }, - { - sql: `DEFINE TABLE person PERMISSIONS FOR select, create, update WHERE public = true FOR delete NONE`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Create: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Update: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Delete: false, - }, - }}}, - }, - { - sql: `DEFINE TABLE person AS SELECT nationality, math.midhinge(age) AS mid FROM users GROUP BY nationality`, - err: "Found 'mid' but field is not an aggregate function, and is not present in GROUP expression", - }, - { - sql: `DEFINE TABLE person AS SELECT nationality, count(*) AS total FROM users WHERE public = true GROUP BY nationality`, - res: &Query{Statements: []Statement{&DefineTableStatement{ - What: Tables{&Table{"person"}}, - Lock: true, - Expr: Fields{ - &Field{ - Expr: &Ident{"nationality"}, - Field: "nationality", - }, - &Field{ - Expr: &FuncExpression{ - Name: "count", - Args: Exprs{&All{}}, - Aggr: true, - }, - Field: "total", - Alias: "total", - }, - }, - From: Tables{ - &Table{TB: "users"}, - }, - Cond: &BinaryExpression{ - LHS: &Ident{"public"}, - Op: EQ, - RHS: true, - }, - Group: Groups{ - &Group{ - Expr: &Ident{"nationality"}, - }, - }, - }}}, - }, - { - sql: `DEFINE TABLE person SCHEMALESS something`, - err: "Found `something` but expected `;`", - }, - { - sql: `DEFINE TABLE person SCHEMAFULL something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE EVENT`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE EVENT temp`, - err: "Found `` but expected `ON`", - }, - { - sql: `DEFINE EVENT temp ON`, - err: "Found `` but expected `table`", - }, - { - sql: `DEFINE EVENT temp ON person`, - err: "Found `` but expected `WHEN`", - }, - { - sql: `DEFINE EVENT temp ON person WHEN`, - err: "Found `` but expected `expression`", - }, - { - sql: `DEFINE EVENT temp ON person WHEN $before.price < $after.price`, - err: "Found `` but expected `THEN`", - }, - { - sql: `DEFINE EVENT temp ON person WHEN $before.price < $after.price THEN`, - err: "Found `` but expected `(`", - }, - { - sql: `DEFINE EVENT temp ON person WHEN $before.price < $after.price THEN (UPDATE $this SET increased = true)`, - res: &Query{Statements: []Statement{&DefineEventStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - When: &BinaryExpression{ - LHS: &Param{"before.price"}, - Op: LT, - RHS: &Param{"after.price"}, - }, - Then: &MultExpression{ - Expr: []Expr{ - &UpdateStatement{ - What: Exprs{&Param{"this"}}, - Data: &DataExpression{[]*ItemExpression{ - { - LHS: &Ident{"increased"}, - Op: EQ, - RHS: true, - }, - }}, - Echo: AFTER, - }, - }, - }, - }}}, - }, - { - sql: `DEFINE EVENT temp ON person WHEN $before.price < $after.price THEN (UPDATE $this SET increased = true; UPDATE $this SET finished = true)`, - res: &Query{Statements: []Statement{&DefineEventStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - When: &BinaryExpression{ - LHS: &Param{"before.price"}, - Op: LT, - RHS: &Param{"after.price"}, - }, - Then: &MultExpression{ - Expr: []Expr{ - &UpdateStatement{ - What: Exprs{&Param{"this"}}, - Data: &DataExpression{[]*ItemExpression{ - { - LHS: &Ident{"increased"}, - Op: EQ, - RHS: true, - }, - }}, - Echo: AFTER, - }, - &UpdateStatement{ - What: Exprs{&Param{"this"}}, - Data: &DataExpression{[]*ItemExpression{ - { - LHS: &Ident{"finished"}, - Op: EQ, - RHS: true, - }, - }}, - Echo: AFTER, - }, - }, - }, - }}}, - }, - { - sql: `DEFINE EVENT temp ON person WHEN $before.price < $after.price THEN (UPDATE $this SET increased = true) something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE FIELD`, - err: "Found `` but expected `name, or expression`", - }, - { - sql: `DEFINE FIELD temp`, - err: "Found `` but expected `ON`", - }, - { - sql: `DEFINE FIELD temp ON`, - err: "Found `` but expected `table`", - }, - { - sql: `DEFINE FIELD temp ON person`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person TYPE`, - err: "Found `` but expected `array, boolean, circle, datetime, number, object, point, polygon, record, string`", - }, - { - sql: `DEFINE FIELD temp ON person TYPE something`, - err: "Found `something` but expected `array, boolean, circle, datetime, number, object, point, polygon, record, string`", - }, - { - sql: `DEFINE FIELD temp ON person TYPE array`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Type: "array", - }}}, - }, - { - sql: `DEFINE FIELD temp ON person TYPE object`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Type: "object", - }}}, - }, - { - sql: `DEFINE FIELD temp ON person TYPE string`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Type: "string", - }}}, - }, - { - sql: `DEFINE FIELD temp ON person TYPE number`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Type: "number", - }}}, - }, - { - sql: `DEFINE FIELD temp ON person TYPE record`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Type: "record", - }}}, - }, - { - sql: `DEFINE FIELD temp ON person TYPE record (item)`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Type: "record", - Kind: "item", - }}}, - }, - { - sql: `DEFINE FIELD temp ON person VALUE`, - err: "Found `` but expected `expression`", - }, - { - sql: `DEFINE FIELD temp ON person VALUE string.uppercase($value)`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Value: &FuncExpression{Name: "string.uppercase", Args: Exprs{&Param{"value"}}}, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person ASSERT`, - err: "Found `` but expected `expression`", - }, - { - sql: `DEFINE FIELD temp ON person ASSERT $value > 0 AND $value < 100`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Assert: &BinaryExpression{ - LHS: &BinaryExpression{ - LHS: &Param{"value"}, - Op: GT, - RHS: 0.0, - }, - Op: AND, - RHS: &BinaryExpression{ - LHS: &Param{"value"}, - Op: LT, - RHS: 100.0, - }, - }, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS SOME`, - err: "Found `SOME` but expected `FOR, NONE, FULL, WHERE`", - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS NONE`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: false, - Create: false, - Update: false, - Delete: false, - }, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS FULL`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: true, - Create: true, - Update: true, - Delete: true, - }, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS WHERE public = true`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Create: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Update: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Delete: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - }, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS FOR select FULL FOR insert, upsert NONE`, - err: "Found `insert` but expected `SELECT, CREATE, UPDATE, DELETE`", - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS FOR select FULL FOR create, update, delete SOME`, - err: "Found `SOME` but expected `FULL, NONE, WHERE`", - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS FOR select FULL FOR create, update, delete NONE`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: true, - Create: false, - Update: false, - Delete: false, - }, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person PERMISSIONS FOR select, create, update WHERE public = true FOR delete NONE`, - res: &Query{Statements: []Statement{&DefineFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Perms: &PermExpression{ - Select: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Create: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Update: &BinaryExpression{LHS: &Ident{"public"}, Op: EQ, RHS: true}, - Delete: false, - }, - }}}, - }, - { - sql: `DEFINE FIELD temp ON person something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `DEFINE INDEX`, - err: "Found `` but expected `name`", - }, - { - sql: `DEFINE INDEX temp`, - err: "Found `` but expected `ON`", - }, - { - sql: `DEFINE INDEX temp ON`, - err: "Found `` but expected `table`", - }, - { - sql: `DEFINE INDEX temp ON person`, - err: "Found `` but expected `COLUMNS`", - }, - { - sql: `DEFINE INDEX temp ON person COLUMNS`, - err: "Found `` but expected `name, or expression`", - }, - { - sql: `DEFINE INDEX temp ON person COLUMNS firstname, lastname`, - res: &Query{Statements: []Statement{&DefineIndexStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Cols: Idents{&Ident{"firstname"}, &Ident{"lastname"}}, - Uniq: false, - }}}, - }, - { - sql: `DEFINE INDEX temp ON person COLUMNS firstname, lastname UNIQUE`, - res: &Query{Statements: []Statement{&DefineIndexStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - Cols: Idents{&Ident{"firstname"}, &Ident{"lastname"}}, - Uniq: true, - }}}, - }, - { - sql: `DEFINE INDEX temp ON person COLUMNS firstname, lastname something UNIQUE`, - err: "Found `something` but expected `;`", - }, - { - sql: `DEFINE INDEX temp ON person COLUMNS firstname, lastname UNIQUE something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Remove(t *testing.T) { - - var tests = []tester{ - { - sql: `REMOVE`, - err: "Found `` but expected `NAMESPACE, DATABASE, LOGIN, TOKEN, SCOPE, TABLE, EVENT, FIELD, INDEX`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE NAMESPACE`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE NAMESPACE 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `REMOVE NAMESPACE 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `REMOVE NAMESPACE test`, - res: &Query{Statements: []Statement{&RemoveNamespaceStatement{ - Name: &Ident{"test"}, - }}}, - }, - { - sql: `REMOVE NAMESPACE test something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE DATABASE`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE DATABASE 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `REMOVE DATABASE 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `REMOVE DATABASE test`, - res: &Query{Statements: []Statement{&RemoveDatabaseStatement{ - Name: &Ident{"test"}, - }}}, - }, - { - sql: `REMOVE DATABASE test something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE LOGIN`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE LOGIN 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `REMOVE LOGIN 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `REMOVE LOGIN test`, - err: "Found `` but expected `ON`", - }, - { - sql: `REMOVE LOGIN test ON`, - err: "Found `` but expected `NAMESPACE, DATABASE`", - }, - { - sql: `REMOVE LOGIN test ON something`, - err: "Found `something` but expected `NAMESPACE, DATABASE`", - }, - { - sql: `REMOVE LOGIN test ON NAMESPACE`, - res: &Query{Statements: []Statement{&RemoveLoginStatement{ - Kind: NAMESPACE, - User: &Ident{"test"}, - }}}, - }, - { - sql: `REMOVE LOGIN test ON DATABASE`, - res: &Query{Statements: []Statement{&RemoveLoginStatement{ - Kind: DATABASE, - User: &Ident{"test"}, - }}}, - }, - { - sql: `REMOVE LOGIN test ON DATABASE something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE TOKEN`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE TOKEN 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `REMOVE TOKEN 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `REMOVE TOKEN test`, - err: "Found `` but expected `ON`", - }, - { - sql: `REMOVE TOKEN test ON`, - err: "Found `` but expected `NAMESPACE, DATABASE, SCOPE`", - }, - { - sql: `REMOVE TOKEN test ON something`, - err: "Found `something` but expected `NAMESPACE, DATABASE, SCOPE`", - }, - { - sql: `REMOVE TOKEN test ON NAMESPACE`, - res: &Query{Statements: []Statement{&RemoveTokenStatement{ - Kind: NAMESPACE, - Name: &Ident{"test"}, - What: &Ident{""}, - }}}, - }, - { - sql: `REMOVE TOKEN test ON DATABASE`, - res: &Query{Statements: []Statement{&RemoveTokenStatement{ - Kind: DATABASE, - Name: &Ident{"test"}, - What: &Ident{""}, - }}}, - }, - { - sql: `REMOVE TOKEN test ON SCOPE`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE TOKEN test ON SCOPE test`, - res: &Query{Statements: []Statement{&RemoveTokenStatement{ - Kind: SCOPE, - Name: &Ident{"test"}, - What: &Ident{"test"}, - }}}, - }, - { - sql: `REMOVE TOKEN test ON DATABASE something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE SCOPE`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE SCOPE 111`, - err: "Found `111` but expected `name`", - }, - { - sql: `REMOVE SCOPE 111.111`, - err: "Found `111.111` but expected `name`", - }, - { - sql: `REMOVE SCOPE test`, - res: &Query{Statements: []Statement{&RemoveScopeStatement{ - Name: &Ident{"test"}, - }}}, - }, - { - sql: `REMOVE SCOPE test something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE TABLE`, - err: "Found `` but expected `table`", - }, - { - sql: `REMOVE TABLE 111`, - err: "Found `111` but expected `table`", - }, - { - sql: `REMOVE TABLE 111.111`, - err: "Found `111.111` but expected `table`", - }, - { - sql: `REMOVE TABLE person`, - res: &Query{Statements: []Statement{&RemoveTableStatement{ - What: Tables{&Table{"person"}}, - }}}, - }, - { - sql: `REMOVE TABLE person something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE EVENT`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE EVENT temp`, - err: "Found `` but expected `ON`", - }, - { - sql: `REMOVE EVENT temp ON`, - err: "Found `` but expected `table`", - }, - { - sql: `REMOVE EVENT temp ON person`, - res: &Query{Statements: []Statement{&RemoveEventStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - }}}, - }, - { - sql: `REMOVE EVENT temp ON person something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE FIELD`, - err: "Found `` but expected `name, or expression`", - }, - { - sql: `REMOVE FIELD temp`, - err: "Found `` but expected `ON`", - }, - { - sql: `REMOVE FIELD temp ON`, - err: "Found `` but expected `table`", - }, - { - sql: `REMOVE FIELD temp ON person`, - res: &Query{Statements: []Statement{&RemoveFieldStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - }}}, - }, - { - sql: `REMOVE FIELD temp ON person something`, - err: "Found `something` but expected `;`", - }, - // ---------------------------------------------------------------------- - { - sql: `REMOVE INDEX`, - err: "Found `` but expected `name`", - }, - { - sql: `REMOVE INDEX temp`, - err: "Found `` but expected `ON`", - }, - { - sql: `REMOVE INDEX temp ON`, - err: "Found `` but expected `table`", - }, - { - sql: `REMOVE INDEX temp ON person`, - res: &Query{Statements: []Statement{&RemoveIndexStatement{ - Name: &Ident{"temp"}, - What: Tables{&Table{"person"}}, - }}}, - }, - { - sql: `REMOVE INDEX temp ON person something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Begin(t *testing.T) { - - var tests = []tester{ - { - sql: `BEGIN`, - str: `BEGIN TRANSACTION`, - res: &Query{Statements: []Statement{&BeginStatement{}}}, - }, - { - sql: `BEGIN something`, - err: "Found `something` but expected `;`", - }, - { - sql: `BEGIN TRANSACTION`, - res: &Query{Statements: []Statement{&BeginStatement{}}}, - }, - { - sql: `BEGIN TRANSACTION something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Cancel(t *testing.T) { - - var tests = []tester{ - { - sql: `CANCEL`, - str: `CANCEL TRANSACTION`, - res: &Query{Statements: []Statement{&CancelStatement{}}}, - }, - { - sql: `CANCEL something`, - err: "Found `something` but expected `;`", - }, - { - sql: `CANCEL TRANSACTION`, - res: &Query{Statements: []Statement{&CancelStatement{}}}, - }, - { - sql: `CANCEL TRANSACTION something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} - -func Test_Parse_Queries_Commit(t *testing.T) { - - var tests = []tester{ - { - sql: `COMMIT`, - str: `COMMIT TRANSACTION`, - res: &Query{Statements: []Statement{&CommitStatement{}}}, - }, - { - sql: `COMMIT something`, - err: "Found `something` but expected `;`", - }, - { - sql: `COMMIT TRANSACTION`, - res: &Query{Statements: []Statement{&CommitStatement{}}}, - }, - { - sql: `COMMIT TRANSACTION something`, - err: "Found `something` but expected `;`", - }, - } - - for _, test := range tests { - testsql(t, test) - } - -} diff --git a/sql/string.go b/sql/string.go deleted file mode 100644 index f8b8e395..00000000 --- a/sql/string.go +++ /dev/null @@ -1,960 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "encoding/json" - "fmt" - "sort" - "strconv" - "strings" - "time" -) - -const ( - _select method = iota - _create - _update - _delete -) - -type method int - -type methods []method - -func (this method) String() string { - switch this { - case _select: - return "select" - case _create: - return "create" - case _update: - return "update" - case _delete: - return "delete" - } - return "" -} - -func (this methods) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -// --------------------------------------------- -// Helpers -// --------------------------------------------- - -func print(s string, a ...interface{}) string { - for k, v := range a { - switch v.(type) { - default: - case nil: - a[k] = "NULL" - case []interface{}: - out, _ := json.Marshal(v) - a[k] = string(out) - case map[string]interface{}: - out, _ := json.Marshal(v) - a[k] = string(out) - } - } - return fmt.Sprintf(s, a...) -} - -func maybe(b bool, v ...interface{}) string { - switch b { - case false: - if len(v) >= 2 { - return fmt.Sprint(v[1]) - } - case true: - if len(v) >= 1 { - return fmt.Sprint(v[0]) - } - } - return "" -} - -func binar(b []byte) string { - return fmt.Sprintf("%q", b) -} - -func quote(s string) string { - t := newToken(s) - switch t { - case ILLEGAL: - if toQuote(s) { - return "`" + s + "`" - } - return s - default: - switch { - case t.isKeyword(): - return "`" + s + "`" - case t.isOperator(): - return "`" + s + "`" - } - return s - } -} - -func toQuote(s string) bool { - for _, c := range s { - switch { - case c >= 'a' && c <= 'z': - continue - case c >= 'A' && c <= 'Z': - continue - case c >= '0' && c <= '9': - continue - case c == '[', c == ']': - continue - case c == '.', c == '*': - continue - case c == '_': - continue - default: - return true - } - } - return false -} - -// --------------------------------------------- -// Statements -// --------------------------------------------- - -func (this OptStatement) String() string { - return print("OPTION %v%v", - quote(this.Name), - maybe(this.What == false, print(" = %v", this.What)), - ) -} - -func (this UseStatement) String() string { - switch { - case len(this.NS) == 0: - return print("USE DATABASE %v", quote(this.DB)) - case len(this.DB) == 0: - return print("USE NAMESPACE %v", quote(this.NS)) - default: - return print("USE NAMESPACE %v DATABASE %v", quote(this.NS), quote(this.DB)) - } -} - -func (this BeginStatement) String() string { - return "BEGIN TRANSACTION" -} - -func (this CancelStatement) String() string { - return "CANCEL TRANSACTION" -} - -func (this CommitStatement) String() string { - return "COMMIT TRANSACTION" -} - -func (this InfoStatement) String() string { - switch this.Kind { - case ALL: - return "INFO FOR ALL" - case NAMESPACE, NS: - return "INFO FOR NAMESPACE" - case DATABASE, DB: - return "INFO FOR DATABASE" - case SCOPE: - return print("INFO FOR SCOPE %s", this.What) - default: - return print("INFO FOR TABLE %s", this.What) - } -} - -func (this RunStatement) String() string { - return print("RUN %v", - this.Expr, - ) -} - -func (this LetStatement) String() string { - return print("LET %v = %v", - this.Name, - this.What, - ) -} - -func (this LiveStatement) String() string { - return print("LIVE SELECT %v%v FROM %v%v%v", - maybe(this.Diff, "DIFF"), - this.Expr, - this.What, - maybe(this.Cond != nil, print(" WHERE %v", this.Cond)), - this.Fetch, - ) -} - -func (this KillStatement) String() string { - return print("KILL %v", - this.What, - ) -} - -func (this ReturnStatement) String() string { - return print("RETURN %v", - this.What, - ) -} - -func (this IfelseStatement) String() string { - m := make([]string, len(this.Cond)) - for k := range this.Cond { - m[k] = print("%v THEN %v", this.Cond[k], this.Then[k]) - } - return print("IF %v%v END", - strings.Join(m, " ELSE IF "), - maybe(this.Else != nil, print(" ELSE %v", this.Else)), - ) -} - -func (this SelectStatement) String() string { - return print("SELECT %v FROM %v%v%v%v%v%v%v%v%v%v", - this.Expr, - this.What, - maybe(this.Cond != nil, print(" WHERE %v", this.Cond)), - maybe(this.Split != nil, print(" SPLIT %v", this.Split)), - this.Group, - this.Order, - maybe(this.Limit != nil, print(" LIMIT %v", this.Limit)), - maybe(this.Start != nil, print(" START %v", this.Start)), - this.Fetch, - maybe(this.Version != nil, print(" VERSION %v", this.Version)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this CreateStatement) String() string { - return print("CREATE %v%v%v%v", - this.What, - maybe(this.Data != nil, print("%v", this.Data)), - maybe(this.Echo != AFTER, print(" RETURN %v", this.Echo)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this UpdateStatement) String() string { - return print("UPDATE %v%v%v%v%v", - this.What, - maybe(this.Data != nil, print("%v", this.Data)), - maybe(this.Cond != nil, print(" WHERE %v", this.Cond)), - maybe(this.Echo != AFTER, print(" RETURN %v", this.Echo)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this DeleteStatement) String() string { - return print("DELETE %v%v%v%v", - this.What, - maybe(this.Cond != nil, print(" WHERE %v", this.Cond)), - maybe(this.Echo != NONE, print(" RETURN %v", this.Echo)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this RelateStatement) String() string { - return print("RELATE %v -> %v -> %v%v%v%v%v", - this.From, - this.Type, - this.With, - maybe(this.Data != nil, print("%v", this.Data)), - maybe(this.Uniq, " UNIQUE"), - maybe(this.Echo != AFTER, print(" RETURN %v", this.Echo)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this InsertStatement) String() string { - return print("INSERT %v INTO %v%v%v", - this.Data, - this.Into, - maybe(this.Echo != AFTER, print(" RETURN %v", this.Echo)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this UpsertStatement) String() string { - return print("UPSERT %v INTO %v%v%v", - this.Data, - this.Into, - maybe(this.Echo != AFTER, print(" RETURN %v", this.Echo)), - maybe(this.Timeout > 0, print(" TIMEOUT %v", this.Timeout.String())), - ) -} - -func (this DefineNamespaceStatement) String() string { - return print("DEFINE NAMESPACE %v", - this.Name, - ) -} - -func (this RemoveNamespaceStatement) String() string { - return print("REMOVE NAMESPACE %v", - this.Name, - ) -} - -func (this DefineDatabaseStatement) String() string { - return print("DEFINE DATABASE %v", - this.Name, - ) -} - -func (this RemoveDatabaseStatement) String() string { - return print("REMOVE DATABASE %v", - this.Name, - ) -} - -func (this DefineLoginStatement) String() string { - return print("DEFINE LOGIN %v ON %v PASSHASH %s", - this.User, - this.Kind, - binar(this.Pass), - ) -} - -func (this RemoveLoginStatement) String() string { - return print("REMOVE LOGIN %v ON %v", - this.User, - this.Kind, - ) -} - -func (this DefineTokenStatement) String() string { - return print("DEFINE TOKEN %v ON %v TYPE %v VALUE %s", - this.Name, - maybe(this.Kind == SCOPE, print("%v %v", this.Kind, this.What), print("%v", this.Kind)), - this.Type, - binar(this.Code), - ) -} - -func (this RemoveTokenStatement) String() string { - return print("REMOVE TOKEN %v ON %v", - this.Name, - maybe(this.Kind == SCOPE, print("%v %v", this.Kind, this.What), print("%v", this.Kind)), - ) -} - -func (this DefineScopeStatement) String() string { - return print("DEFINE SCOPE %v%v%v%v%v%v%v", - this.Name, - maybe(this.Time > 0, print(" SESSION %v", this.Time)), - maybe(this.Signup != nil, print(" SIGNUP AS %v", this.Signup)), - maybe(this.Signin != nil, print(" SIGNIN AS %v", this.Signin)), - maybe(this.Connect != nil, print(" CONNECT AS %v", this.Connect)), - maybe(this.OnSignup != nil, print(" ON SIGNUP %v", this.OnSignup)), - maybe(this.OnSignin != nil, print(" ON SIGNIN %v", this.OnSignin)), - ) -} - -func (this RemoveScopeStatement) String() string { - return print("REMOVE SCOPE %v", - this.Name, - ) -} - -func (this DefineTableStatement) String() (s string) { - w := maybe(this.Cond != nil, print(" WHERE %v", this.Cond)) - return print("DEFINE TABLE %v%v%v%v%v%v", - maybe(this.Name != nil, print("%s", this.Name), print("%s", this.What)), - maybe(this.Full, " SCHEMAFULL"), - maybe(this.Vers, " VERSIONED"), - maybe(this.Drop, " DROP"), - maybe(this.Lock, print(" AS SELECT %v FROM %v%v%v", this.Expr, this.From, w, this.Group)), - maybe(this.Perms != nil, this.Perms), - ) -} - -func (this RemoveTableStatement) String() string { - return print("REMOVE TABLE %v", - this.What, - ) -} - -func (this DefineEventStatement) String() string { - return print("DEFINE EVENT %v ON %v WHEN %v THEN %v", - this.Name, - this.What, - this.When, - this.Then, - ) -} - -func (this RemoveEventStatement) String() string { - return print("REMOVE EVENT %v ON %v", - this.Name, - this.What, - ) -} - -func (this DefineFieldStatement) String() string { - return print("DEFINE FIELD %v ON %v%v%v%v%v%v%v", - this.Name, - this.What, - maybe(this.Type != "", print(" TYPE %v", this.Type)), - maybe(this.Kind != "", print(" (%v)", quote(this.Kind))), - maybe(this.Value != nil, print(" VALUE %v", this.Value)), - maybe(this.Assert != nil, print(" ASSERT %v", this.Assert)), - maybe(this.Priority != 0, print(" PRIORITY %v", this.Priority)), - maybe(this.Perms != nil, this.Perms), - ) -} - -func (this RemoveFieldStatement) String() string { - return print("REMOVE FIELD %v ON %v", - this.Name, - this.What, - ) -} - -func (this DefineIndexStatement) String() string { - return print("DEFINE INDEX %v ON %v COLUMNS %v%v", - this.Name, - this.What, - this.Cols, - maybe(this.Uniq, " UNIQUE"), - ) -} - -func (this RemoveIndexStatement) String() string { - return print("REMOVE INDEX %v ON %v", - this.Name, - this.What, - ) -} - -// --------------------------------------------- -// Literals -// --------------------------------------------- - -func (this Exprs) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = print("%v", v) - } - return strings.Join(m, ", ") -} - -func (this All) String() string { - return "*" -} - -func (this Any) String() string { - return "?" -} - -func (this Null) String() string { - return "NULL" -} - -func (this Void) String() string { - return "VOID" -} - -func (this Empty) String() string { - return "EMPTY" -} - -// --------------------------------------------- -// Field -// --------------------------------------------- - -func (this Fields) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return print("%v", - strings.Join(m, ", "), - ) -} - -func (this Field) String() string { - return print("%v%v", - this.Expr, - maybe(this.Alias != "", print(" AS %s", quote(this.Alias))), - ) -} - -// --------------------------------------------- -// Group -// --------------------------------------------- - -func (this Groups) String() string { - if len(this) == 0 { - return "" - } - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return print(" GROUP BY %v", - strings.Join(m, ", "), - ) -} - -func (this Group) String() string { - return print("%v", - this.Expr, - ) -} - -// --------------------------------------------- -// Order -// --------------------------------------------- - -func (this Orders) String() string { - if len(this) == 0 { - return "" - } - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return print(" ORDER BY %v", - strings.Join(m, ", "), - ) -} - -func (this Order) String() string { - return print("%v %v%v", - this.Expr, - maybe(this.Dir, "ASC", "DESC"), - maybe(!this.Tag.IsRoot(), print(" COLLATE %s", this.Tag.String())), - ) -} - -// --------------------------------------------- -// Fetch -// --------------------------------------------- - -func (this Fetchs) String() string { - if len(this) == 0 { - return "" - } - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return print(" FETCH %v", - strings.Join(m, ", "), - ) -} - -func (this Fetch) String() string { - return print("%v", - this.Expr, - ) -} - -// --------------------------------------------- -// Param -// --------------------------------------------- - -func (this Params) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Param) String() string { - return print("$%v", this.VA) -} - -// --------------------------------------------- -// Ident -// --------------------------------------------- - -func (this Idents) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Ident) String() string { - return quote(this.VA) -} - -// --------------------------------------------- -// Value -// --------------------------------------------- - -func (this Values) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Value) String() string { - return print(`"%v"`, this.VA) -} - -// --------------------------------------------- -// Regex -// --------------------------------------------- - -func (this Regexs) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Regex) String() string { - return print("/%v/", this.VA) -} - -// --------------------------------------------- -// Table -// --------------------------------------------- - -func (this Tables) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Table) String() string { - return quote(this.TB) -} - -// --------------------------------------------- -// Batch -// --------------------------------------------- - -func (this Batchs) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Batch) String() string { - return print("batch(%v, [%v]", this.TB, this.BA) -} - -// --------------------------------------------- -// Model -// --------------------------------------------- - -func (this Model) String() string { - switch { - case this.INC == 0: - max := strconv.FormatFloat(this.MAX, 'f', -1, 64) - return print("|%s:%s|", quote(this.TB), max) - case this.INC == 1: - min := strconv.FormatFloat(this.MIN, 'f', -1, 64) - max := strconv.FormatFloat(this.MAX, 'f', -1, 64) - return print("|%s:%s..%s|", quote(this.TB), min, max) - default: - inc := strconv.FormatFloat(this.INC, 'f', -1, 64) - min := strconv.FormatFloat(this.MIN, 'f', -1, 64) - max := strconv.FormatFloat(this.MAX, 'f', -1, 64) - return print("|%s:%s,%s..%s|", quote(this.TB), min, inc, max) - } -} - -// --------------------------------------------- -// Thing -// --------------------------------------------- - -func (this Things) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Thing) String() string { - tb := this.TB - if toQuote(this.TB) { - tb = print("⟨%v⟩", this.TB) - } - id := this.ID - switch v := this.ID.(type) { - case int64: - id = strconv.FormatInt(v, 10) - case float64: - id = strconv.FormatFloat(v, 'f', -1, 64) - case time.Time: - id = print("⟨%v⟩", v.Format(RFCNano)) - case string: - if toQuote(v) { - id = print("⟨%v⟩", v) - } - default: - if toQuote(fmt.Sprint(v)) { - id = print("⟨%v⟩", v) - } - } - return print("%v:%v", tb, id) -} - -// --------------------------------------------- -// Point -// --------------------------------------------- - -func (this Points) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Point) String() string { - return print("geo.point(%v,%v)", this.LA, this.LO) -} - -func (this Point) JSON() string { - return fmt.Sprintf(`[%v,%v]`, this.LA, this.LO) -} - -// --------------------------------------------- -// Circle -// --------------------------------------------- - -func (this Circles) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Circle) String() string { - return print("geo.circle(%v,%v)", this.CE, this.RA) -} - -func (this Circle) JSON() string { - return fmt.Sprintf(`{"type":"circle","center":%v,"radius":%v}`, this.CE.JSON(), this.RA) -} - -// --------------------------------------------- -// Polygon -// --------------------------------------------- - -func (this Polygons) String() string { - m := make([]string, len(this)) - for k, v := range this { - m[k] = v.String() - } - return strings.Join(m, ", ") -} - -func (this Polygon) String() string { - var m []string - for _, v := range this.PS { - m = append(m, v.String()) - } - return print("geo.polygon(%v)", - strings.Join(m, ", "), - ) -} - -func (this Polygon) JSON() string { - var m []string - for _, p := range this.PS { - m = append(m, p.JSON()) - } - return fmt.Sprintf(`{"type":"polygon","points":[%v]}`, strings.Join(m, ",")) -} - -// --------------------------------------------- -// Expressions -// --------------------------------------------- - -func (this SubExpression) String() string { - switch this.Expr.(type) { - case *IfelseStatement: - return print("%v", this.Expr) - default: - return print("(%v)", this.Expr) - } -} - -func (this MultExpression) String() string { - m := make([]string, len(this.Expr)) - for k := range this.Expr { - m[k] = print("%v", this.Expr[k]) - } - return print("(%v)", - strings.Join(m, "; "), - ) -} - -func (this FuncExpression) String() string { - return print("%v(%v)", - this.Name, - this.Args, - ) -} - -func (this ItemExpression) String() string { - return print("%v %v %v", - this.LHS, - this.Op, - this.RHS, - ) -} - -func (this BinaryExpression) String() string { - return print("%v %v %v", - this.LHS, - this.Op, - this.RHS, - ) -} - -func (this PathExpression) String() string { - var m []string - for _, v := range this.Expr { - m = append(m, print("%v", v)) - } - return strings.Join(m, "") -} - -func (this PartExpression) String() string { - return print("%v", - this.Part, - ) -} - -func (this JoinExpression) String() string { - return print("%v", - this.Join, - ) -} - -func (this SubpExpression) String() string { - return print("(%v%v%v)", - this.What, - maybe(this.Name != nil, print(" AS %v", this.Name)), - maybe(this.Cond != nil, print(" WHERE %v", this.Cond)), - ) -} - -func (this DataExpression) String() string { - var m []string - for _, v := range this.Data { - m = append(m, v.String()) - } - return print(" SET %v", - strings.Join(m, ", "), - ) -} - -func (this DiffExpression) String() string { - return print(" DIFF %v", - this.Data, - ) -} - -func (this MergeExpression) String() string { - return print(" MERGE %v", - this.Data, - ) -} - -func (this ContentExpression) String() string { - return print(" CONTENT %v", - this.Data, - ) -} - -func (this PermExpression) String() string { - - var k, o string - - a := []string{} - m := map[string]methods{} - - if v, ok := this.Select.(bool); ok { - k = maybe(v, "FULL", "NONE") - m[k] = append(m[k], _select) - } else { - k = print("WHERE %v", this.Select) - m[k] = append(m[k], _select) - } - - if v, ok := this.Create.(bool); ok { - k = maybe(v, "FULL", "NONE") - m[k] = append(m[k], _create) - } else { - k = print("WHERE %v", this.Create) - m[k] = append(m[k], _create) - } - - if v, ok := this.Update.(bool); ok { - k = maybe(v, "FULL", "NONE") - m[k] = append(m[k], _update) - } else { - k = print("WHERE %v", this.Update) - m[k] = append(m[k], _update) - } - - if v, ok := this.Delete.(bool); ok { - k = maybe(v, "FULL", "NONE") - m[k] = append(m[k], _delete) - } else { - k = print("WHERE %v", this.Delete) - m[k] = append(m[k], _delete) - } - - if len(m) == 1 { - for k := range m { - return print(" PERMISSIONS %v", k) - } - } - - for k := range m { - a = append(a, k) - } - - sort.Slice(a, func(i, j int) bool { - return m[a[i]][0] < m[a[j]][0] - }) - - for _, v := range a { - o += print(" FOR %v %v", m[v], v) - } - - return print(" PERMISSIONS%v", o) - -} diff --git a/sql/table.go b/sql/table.go deleted file mode 100644 index 6a548ec6..00000000 --- a/sql/table.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineTableStatement() (stmt *DefineTableStatement, err error) { - - stmt = &DefineTableStatement{} - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - for { - - tok, _, exi := p.mightBe(DROP, SCHEMAFULL, SCHEMALESS, VERSIONED, UNVERSIONED, PERMISSIONS, AS) - if !exi { - break - } - - if is(tok, DROP) { - stmt.Drop = true - } - - if is(tok, SCHEMAFULL) { - stmt.Full = true - } - - if is(tok, SCHEMALESS) { - stmt.Full = false - } - - if is(tok, VERSIONED) { - stmt.Vers = true - } - - if is(tok, UNVERSIONED) { - stmt.Vers = false - } - - if is(tok, PERMISSIONS) { - if stmt.Perms, err = p.parsePerms(); err != nil { - return nil, err - } - } - - if is(tok, AS) { - - stmt.Lock = true - - _, _, _ = p.mightBe(LPAREN) - - _, _, err = p.shouldBe(SELECT) - if err != nil { - return nil, err - } - - if stmt.Expr, err = p.parseFields(); err != nil { - return nil, err - } - - _, _, err = p.shouldBe(FROM) - if err != nil { - return nil, err - } - - if stmt.From, err = p.parseTables(); err != nil { - return nil, err - } - - if stmt.Cond, err = p.parseCond(); err != nil { - return nil, err - } - - if stmt.Group, err = p.parseGroup(); err != nil { - return nil, err - } - - _, _, _ = p.mightBe(RPAREN) - - if err = checkExpression(rolls, stmt.Expr, stmt.Group); err != nil { - return nil, err - } - - } - - } - - return - -} - -func (p *parser) parseRemoveTableStatement() (stmt *RemoveTableStatement, err error) { - - stmt = &RemoveTableStatement{} - - if stmt.What, err = p.parseTables(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/token.go b/sql/token.go deleted file mode 100644 index 064926b3..00000000 --- a/sql/token.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseDefineTokenStatement() (stmt *DefineTokenStatement, err error) { - - stmt = &DefineTokenStatement{} - - stmt.What = &Ident{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.Kind, _, err = p.shouldBe(NAMESPACE, DATABASE, SCOPE); err != nil { - return nil, err - } - - if is(stmt.Kind, SCOPE) { - if stmt.What, err = p.parseIdent(); err != nil { - return nil, err - } - } - - for { - - tok, _, exi := p.mightBe(TYPE, VALUE) - if !exi { - break - } - - if is(tok, TYPE) { - if stmt.Type, err = p.parseAlgorithm(); err != nil { - return nil, err - } - } - - if is(tok, VALUE) { - if stmt.Code, err = p.parseBinary(); err != nil { - return nil, err - } - } - - } - - if stmt.Type == "" { - return nil, &ParseError{Found: "", Expected: []string{"TYPE"}} - } - - if len(stmt.Code) == 0 { - return nil, &ParseError{Found: "", Expected: []string{"VALUE"}} - } - - return - -} - -func (p *parser) parseRemoveTokenStatement() (stmt *RemoveTokenStatement, err error) { - - stmt = &RemoveTokenStatement{} - - stmt.What = &Ident{} - - if stmt.Name, err = p.parseIdent(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(ON); err != nil { - return nil, err - } - - if stmt.Kind, _, err = p.shouldBe(NAMESPACE, DATABASE, SCOPE); err != nil { - return nil, err - } - - if is(stmt.Kind, SCOPE) { - if stmt.What, err = p.parseIdent(); err != nil { - return nil, err - } - } - - return - -} diff --git a/sql/tokens.go b/sql/tokens.go deleted file mode 100644 index fcf1a903..00000000 --- a/sql/tokens.go +++ /dev/null @@ -1,474 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import "strings" - -// Token defines a lexical token -type Token int16 - -const ( - - // special - - ILLEGAL Token = iota - EOF - WS - - // literals - - literalsBeg - - DATE // 1970-01-01 - TIME // 1970-01-01T00:00:00+00:00 - JSON // {"test":true} - EXPR // something[0].value - IDENT // something - THING // @class:id - MODEL // [person|1..1000] - STRING // "something" - REGION // "a multiline \n string" - NUMBER // 123456 - DOUBLE // 123.456 - REGEX // /.*/ - ARRAY // [0,1,2] - DURATION // 13h - PARAM // $1 - - OEDGE // -> - IEDGE // <- - BEDGE // <-> - - DOT // . - COMMA // , - QMARK // ? - LPAREN // ( - RPAREN // ) - LBRACK // [ - RBRACK // ] - COLON // : - SEMICOLON // ; - - literalsEnd - - // operators - - operatorBeg - - ADD // + - SUB // - - MUL // * - DIV // / - INC // += - DEC // -= - - EQ // = - EEQ // == - EXC // ! - NEQ // != - NEE // !== - ANY // ?= - LT // < - LTE // <= - GT // > - GTE // >= - SIN // ∋ - SNI // ∌ - INS // ∈ - NIS // ∉ - MAT // ~ - NAT // !~ - MAY // ?~ - - operatorEnd - - // keywords - - keywordsBeg - - AFTER - ALL - ALLCONTAINEDIN - AND - AS - ASC - ASSERT - AT - BEFORE - BEGIN - BOTH - BY - CANCEL - COLLATE - COLUMNS - COMMIT - CONNECT - CONTAINS - CONTAINSALL - CONTAINSNONE - CONTAINSSOME - CONTENT - CREATE - DATABASE - DB - DEFINE - DELETE - DESC - DIFF - DROP - ELSE - EMPTY - END - EVENT - FALSE - FETCH - FIELD - FOR - FROM - FULL - GROUP - IF - IN - INDEX - INFO - INSERT - INTO - IS - KILL - LET - LIMIT - LIVE - LOGIN - MERGE - MISSING - NAMESPACE - NONE - NONECONTAINEDIN - NOT - NS - NULL - NUMERIC - ON - OPTION - OR - ORDER - PARALLEL - PASSHASH - PASSWORD - PERMISSIONS - PRIORITY - RAND - RELATE - REMOVE - RETURN - RUN - SCHEMAFULL - SCHEMALESS - SCOPE - SELECT - SESSION - SET - SIGNIN - SIGNUP - SOMECONTAINEDIN - SPLIT - START - TABLE - THEN - TIMEOUT - TO - TOKEN - TRANSACTION - TRUE - TYPE - UNIQUE - UNVERSIONED - UPDATE - UPSERT - USE - VALUE - VERSION - VERSIONED - VOID - WHEN - WHERE - WITH - - keywordsEnd -) - -var tokens = [...]string{ - - ILLEGAL: "ILLEGAL", - EOF: "EOF", - WS: "WS", - - // literals - - DATE: "DATE", - TIME: "TIME", - JSON: "JSON", - EXPR: "EXPR", - IDENT: "IDENT", - THING: "THING", - MODEL: "MODEL", - STRING: "STRING", - REGION: "REGION", - NUMBER: "NUMBER", - DOUBLE: "DOUBLE", - REGEX: "REGEX", - ARRAY: "ARRAY", - DURATION: "DURATION", - PARAM: "PARAM", - - OEDGE: "->", - IEDGE: "<-", - BEDGE: "<->", - - DOT: ".", - COMMA: ",", - QMARK: "?", - LPAREN: "(", - RPAREN: ")", - LBRACK: "[", - RBRACK: "]", - COLON: ":", - SEMICOLON: ";", - - // operators - - ADD: "+", - SUB: "-", - MUL: "*", - DIV: "/", - INC: "+=", - DEC: "-=", - - EQ: "=", - EEQ: "==", - EXC: "!", - NEQ: "!=", - NEE: "!==", - ANY: "?=", - LT: "<", - LTE: "<=", - GT: ">", - GTE: ">=", - SIN: "∋", - SNI: "∌", - INS: "∈", - NIS: "∉", - MAT: "~", - NAT: "!~", - MAY: "?~", - - // keywords - - AFTER: "AFTER", - ALL: "ALL", - ALLCONTAINEDIN: "ALLCONTAINEDIN", - AND: "AND", - AS: "AS", - ASC: "ASC", - ASSERT: "ASSERT", - AT: "AT", - BEFORE: "BEFORE", - BEGIN: "BEGIN", - BOTH: "BOTH", - BY: "BY", - CANCEL: "CANCEL", - COLLATE: "COLLATE", - COLUMNS: "COLUMNS", - COMMIT: "COMMIT", - CONNECT: "CONNECT", - CONTAINS: "CONTAINS", - CONTAINSALL: "CONTAINSALL", - CONTAINSNONE: "CONTAINSNONE", - CONTAINSSOME: "CONTAINSSOME", - CONTENT: "CONTENT", - CREATE: "CREATE", - DATABASE: "DATABASE", - DB: "DB", - DEFINE: "DEFINE", - DELETE: "DELETE", - DESC: "DESC", - DIFF: "DIFF", - DROP: "DROP", - ELSE: "ELSE", - EMPTY: "EMPTY", - END: "END", - EVENT: "EVENT", - FALSE: "FALSE", - FETCH: "FETCH", - FIELD: "FIELD", - FOR: "FOR", - FROM: "FROM", - FULL: "FULL", - GROUP: "GROUP", - IF: "IF", - IN: "IN", - INDEX: "INDEX", - INFO: "INFO", - INSERT: "INSERT", - INTO: "INTO", - IS: "IS", - KILL: "KILL", - LET: "LET", - LIMIT: "LIMIT", - LIVE: "LIVE", - LOGIN: "LOGIN", - MERGE: "MERGE", - MISSING: "MISSING", - NAMESPACE: "NAMESPACE", - NONE: "NONE", - NONECONTAINEDIN: "NONECONTAINEDIN", - NOT: "NOT", - NS: "NS", - NULL: "NULL", - NUMERIC: "NUMERIC", - ON: "ON", - OPTION: "OPTION", - OR: "OR", - ORDER: "ORDER", - PARALLEL: "PARALLEL", - PASSHASH: "PASSHASH", - PASSWORD: "PASSWORD", - PERMISSIONS: "PERMISSIONS", - PRIORITY: "PRIORITY", - RAND: "RAND", - RELATE: "RELATE", - REMOVE: "REMOVE", - RETURN: "RETURN", - RUN: "RUN", - SCHEMAFULL: "SCHEMAFULL", - SCHEMALESS: "SCHEMALESS", - SCOPE: "SCOPE", - SELECT: "SELECT", - SESSION: "SESSION", - SET: "SET", - SIGNIN: "SIGNIN", - SIGNUP: "SIGNUP", - SOMECONTAINEDIN: "SOMECONTAINEDIN", - SPLIT: "SPLIT", - START: "START", - TABLE: "TABLE", - THEN: "THEN", - TIMEOUT: "TIMEOUT", - TO: "TO", - TOKEN: "TOKEN", - TRANSACTION: "TRANSACTION", - TRUE: "TRUE", - TYPE: "TYPE", - UNIQUE: "UNIQUE", - UNVERSIONED: "UNVERSIONED", - UPDATE: "UPDATE", - UPSERT: "UPSERT", - USE: "USE", - VALUE: "VALUE", - VERSION: "VERSION", - VERSIONED: "VERSIONED", - VOID: "VOID", - WHEN: "WHEN", - WHERE: "WHERE", - WITH: "WITH", -} - -var literals map[string]Token -var operator map[string]Token -var keywords map[string]Token - -func init() { - - literals = make(map[string]Token) - for tok := literalsBeg + 1; tok < literalsEnd; tok++ { - literals[tokens[tok]] = tok - } - - operator = make(map[string]Token) - for tok := operatorBeg + 1; tok < operatorEnd; tok++ { - operator[tokens[tok]] = tok - } - - keywords = make(map[string]Token) - for tok := keywordsBeg + 1; tok < keywordsEnd; tok++ { - keywords[tokens[tok]] = tok - } - -} - -func lookup(lookups []Token) (literals []string) { - for _, token := range lookups { - literals = append(literals, token.String()) - } - return -} - -func (tok Token) precedence() int { - - switch tok { - case OR, AND: - return 1 - case EQ, NEQ, EEQ, NEE, - LT, LTE, GT, GTE, - ANY, SIN, SNI, INS, NIS, MAT, NAT, MAY, - CONTAINSALL, CONTAINSNONE, CONTAINSSOME, - ALLCONTAINEDIN, NONECONTAINEDIN, SOMECONTAINEDIN: - return 2 - case ADD, SUB: - return 3 - case MUL, DIV: - return 4 - } - - return 0 - -} - -func newToken(s string) Token { - for k, v := range tokens { - if len(v) == len(s) { - if strings.EqualFold(v, s) { - return Token(k) - } - } - } - return ILLEGAL -} - -func (tok Token) String() string { - if tok >= 0 && tok < Token(len(tokens)) { - return tokens[tok] - } - return "" -} - -func (this Token) MarshalText() (data []byte, err error) { - return []byte(this.String()), err -} - -func (this Token) MarshalBinary() (data []byte, err error) { - return []byte(this.String()), err -} - -func (this *Token) UnmarshalBinary(data []byte) (err error) { - *this = newToken(string(data)) - return err -} - -func (tok Token) isLiteral() bool { return tok > literalsBeg && tok < literalsEnd } - -func (tok Token) isKeyword() bool { return tok > keywordsBeg && tok < keywordsEnd } - -func (tok Token) isOperator() bool { return tok > operatorBeg && tok < operatorEnd } diff --git a/sql/trans.go b/sql/trans.go deleted file mode 100644 index 632b9611..00000000 --- a/sql/trans.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseBeginStatement() (stmt *BeginStatement, err error) { - - stmt = &BeginStatement{} - - _, _, _ = p.mightBe(TRANSACTION) - - return - -} - -func (p *parser) parseCancelStatement() (stmt *CancelStatement, err error) { - - stmt = &CancelStatement{} - - _, _, _ = p.mightBe(TRANSACTION) - - return - -} - -func (p *parser) parseCommitStatement() (stmt *CommitStatement, err error) { - - stmt = &CommitStatement{} - - _, _, _ = p.mightBe(TRANSACTION) - - return - -} diff --git a/sql/update.go b/sql/update.go deleted file mode 100644 index a984379b..00000000 --- a/sql/update.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseUpdateStatement() (stmt *UpdateStatement, err error) { - - stmt = &UpdateStatement{} - - if stmt.What, err = p.parseWhat(); err != nil { - return nil, err - } - - if stmt.Data, err = p.parseData(); err != nil { - return nil, err - } - - if stmt.Cond, err = p.parseCond(); err != nil { - return nil, err - } - - if stmt.Echo, err = p.parseEcho(AFTER); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/upsert.go b/sql/upsert.go deleted file mode 100644 index 423aa700..00000000 --- a/sql/upsert.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseUpsertStatement() (stmt *UpsertStatement, err error) { - - stmt = &UpsertStatement{} - - if stmt.Data, err = p.parseExpr(); err != nil { - return nil, err - } - - if _, _, err = p.shouldBe(INTO); err != nil { - return nil, err - } - - _, _, _ = p.mightBe(TABLE) - - if stmt.Into, err = p.parseTable(); err != nil { - return nil, err - } - - if stmt.Echo, err = p.parseEcho(AFTER); err != nil { - return nil, err - } - - if stmt.Timeout, err = p.parseTimeout(); err != nil { - return nil, err - } - - return - -} diff --git a/sql/use.go b/sql/use.go deleted file mode 100644 index 384b536f..00000000 --- a/sql/use.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -func (p *parser) parseUseStatement() (stmt *UseStatement, err error) { - - stmt = &UseStatement{} - - var tok Token - var exi bool - - tok, _, err = p.shouldBe(NAMESPACE, DATABASE, NS, DB) - if err != nil { - return nil, err - } - - for { - - if is(tok, NAMESPACE, NS) { - - _, stmt.NS, err = p.shouldBe(IDENT, STRING, NUMBER, DOUBLE, DATE, TIME) - if err != nil { - return - } - - if len(stmt.NS) == 0 { - return nil, &ParseError{Expected: []string{"namespace name"}, Found: stmt.NS} - } - - } - - if is(tok, DATABASE, DB) { - - _, stmt.DB, err = p.shouldBe(IDENT, STRING, NUMBER, DOUBLE, DATE, TIME) - if err != nil { - return - } - - if len(stmt.DB) == 0 { - return nil, &ParseError{Expected: []string{"database name"}, Found: stmt.DB} - } - - } - - tok, _, exi = p.mightBe(NAMESPACE, NS, DATABASE, DB) - if !exi { - break - } - - } - - return - -} diff --git a/sql/util.go b/sql/util.go deleted file mode 100644 index 200bd934..00000000 --- a/sql/util.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sql - -import ( - "fmt" - "strconv" - "strings" - "time" - - "github.com/hjson/hjson-go" -) - -func in(token Token, tokens []Token) bool { - - for _, t := range tokens { - if token == t { - return true - } - } - - return false - -} - -func is(token Token, tokens ...Token) bool { - - for _, t := range tokens { - if token == t { - return true - } - } - - return false - -} - -func contains(search string, strings []string) bool { - - for _, str := range strings { - if str == search { - return true - } - } - - return false - -} - -func (p *parser) declare(tok Token, lit string) (interface{}, error) { - - if val := p.hold(tok); val != nil { - return val, nil - } - - switch tok { - - case TRUE: - return true, nil - - case FALSE: - return false, nil - - case MUL: - return new(All), nil - - case QMARK: - return new(Any), nil - - case NULL: - return new(Null), nil - - case VOID: - return new(Void), nil - - case MISSING: - return new(Void), nil - - case EMPTY: - return new(Empty), nil - - case EXPR: - return NewIdent(lit), nil - - case IDENT: - return NewIdent(lit), nil - - case TABLE: - return NewTable(lit), nil - - case PARAM: - return NewParam(lit), nil - - case REGEX: - return NewRegex(lit), nil - - case STRING: - return NewValue(lit), nil - - case REGION: - return NewValue(lit), nil - - case DATE: - return time.Parse(RFCDate, lit) - - case TIME: - return time.Parse(RFCTime, lit) - - case NUMBER: - val, err := strconv.ParseFloat(lit, 64) - if err != nil { - return val, fmt.Errorf("Invalid number: %s", lit) - } - return val, nil - - case DOUBLE: - val, err := strconv.ParseFloat(lit, 64) - if err != nil { - return val, fmt.Errorf("Invalid number: %s", lit) - } - return val, nil - - case DURATION: - var mul time.Duration - switch { - default: - mul = 1 - case strings.HasSuffix(lit, "d"): - mul, lit = 24, strings.Replace(lit, "d", "h", -1) - case strings.HasSuffix(lit, "w"): - mul, lit = 168, strings.Replace(lit, "w", "h", -1) - } - val, err := time.ParseDuration(lit) - if err != nil { - return val, fmt.Errorf("Invalid duration: %s", lit) - } - return val * mul, nil - - case ARRAY: - var j []interface{} - hjson.Unmarshal([]byte(lit), &j) - if j == nil { - return j, fmt.Errorf("Invalid JSON: %s", lit) - } - return j, nil - - case JSON: - var j map[string]interface{} - hjson.Unmarshal([]byte(lit), &j) - if j == nil { - return j, fmt.Errorf("Invalid JSON: %s", lit) - } - return j, nil - - } - - return lit, nil - -} diff --git a/txn/db.go b/txn/db.go deleted file mode 100644 index 98f7d689..00000000 --- a/txn/db.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllDB(ctx context.Context, ns string) (out []*sql.DefineDatabaseStatement, err error) { - - var kvs []kvs.KV - - key := &keys.DB{KV: cnf.Settings.DB.Base, NS: ns, DB: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineDatabaseStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetDB(ctx context.Context, ns, db string) (val *sql.DefineDatabaseStatement, err error) { - - if out, ok := t.get(_db, db); ok { - return out.(*sql.DefineDatabaseStatement), nil - } - - var kv kvs.KV - - key := &keys.DB{KV: cnf.Settings.DB.Base, NS: ns, DB: db} - - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorDBNotFound - } - - val = &sql.DefineDatabaseStatement{} - val.Decode(kv.Val()) - - t.set(_db, db, val) - - return - -} - -func (t *TX) AddDB(ctx context.Context, ns, db string) (val *sql.DefineDatabaseStatement, err error) { - - if out, ok := t.get(_db, db); ok { - return out.(*sql.DefineDatabaseStatement), nil - } - - if _, err = t.AddNS(ctx, ns); err != nil { - return - } - - var kv kvs.KV - - key := &keys.DB{KV: cnf.Settings.DB.Base, NS: ns, DB: db} - - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return - } - - if kv != nil && kv.Exi() { - val = &sql.DefineDatabaseStatement{} - val.Decode(kv.Val()) - t.set(_db, db, val) - return - } - - val = &sql.DefineDatabaseStatement{Name: sql.NewIdent(db)} - t.PutC(ctx, 0, key.Encode(), val.Encode(), nil) - - t.set(_db, db, val) - - return - -} - -func (t *TX) DelDB(ns, db string) { - - t.del(_db, db) - -} diff --git a/txn/dt.go b/txn/dt.go deleted file mode 100644 index f7296d84..00000000 --- a/txn/dt.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllDT(ctx context.Context, ns, db string) (out []*sql.DefineTokenStatement, err error) { - - var kvs []kvs.KV - - key := &keys.DT{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TK: keys.Ignore} - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineTokenStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetDT(ctx context.Context, ns, db, tk string) (val *sql.DefineTokenStatement, err error) { - - var kv kvs.KV - - key := &keys.DT{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TK: tk} - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorDTNotFound - } - - val = &sql.DefineTokenStatement{} - val.Decode(kv.Val()) - - return - -} diff --git a/txn/du.go b/txn/du.go deleted file mode 100644 index 86b9b090..00000000 --- a/txn/du.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllDU(ctx context.Context, ns, db string) (out []*sql.DefineLoginStatement, err error) { - - var kvs []kvs.KV - - key := &keys.DU{KV: cnf.Settings.DB.Base, NS: ns, DB: db, US: keys.Ignore} - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineLoginStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetDU(ctx context.Context, ns, db, us string) (val *sql.DefineLoginStatement, err error) { - - var kv kvs.KV - - key := &keys.DU{KV: cnf.Settings.DB.Base, NS: ns, DB: db, US: us} - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorDUNotFound - } - - val = &sql.DefineLoginStatement{} - val.Decode(kv.Val()) - - return - -} diff --git a/txn/err.go b/txn/err.go deleted file mode 100644 index 88e208de..00000000 --- a/txn/err.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import "errors" - -var ( - ErrorNSNotFound = errors.New("The namespace does not exist") - ErrorNTNotFound = errors.New("The namespace token does not exist") - ErrorNUNotFound = errors.New("The namespace user does not exist") - ErrorDBNotFound = errors.New("The database does not exist") - ErrorDTNotFound = errors.New("The database token does not exist") - ErrorDUNotFound = errors.New("The database user does not exist") - ErrorSCNotFound = errors.New("The scope does not exist") - ErrorSTNotFound = errors.New("The scope token does not exist") - ErrorTBNotFound = errors.New("The table does not exist") - ErrorEVNotFound = errors.New("The event does not exist") - ErrorFDNotFound = errors.New("The field does not exist") - ErrorIXNotFound = errors.New("The index does not exist") - ErrorFTNotFound = errors.New("The table does not exist") - ErrorLVNotFound = errors.New("The query does not exist") -) diff --git a/txn/ev.go b/txn/ev.go deleted file mode 100644 index a6496950..00000000 --- a/txn/ev.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllEV(ctx context.Context, ns, db, tb string) (out []*sql.DefineEventStatement, err error) { - - if out, ok := t.get(_ev, tb); ok { - return out.([]*sql.DefineEventStatement), nil - } - - var kvs []kvs.KV - - key := &keys.EV{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb, EV: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineEventStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - t.set(_ev, tb, out) - - return - -} - -func (t *TX) DelEV(ns, db, tb, ev string) { - - t.del(_ev, tb) - -} diff --git a/txn/fd.go b/txn/fd.go deleted file mode 100644 index eae56f94..00000000 --- a/txn/fd.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllFD(ctx context.Context, ns, db, tb string) (out []*sql.DefineFieldStatement, err error) { - - if out, ok := t.get(_fd, tb); ok { - return out.([]*sql.DefineFieldStatement), nil - } - - var kvs []kvs.KV - - key := &keys.FD{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb, FD: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineFieldStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - t.set(_fd, tb, out) - - return - -} - -func (t *TX) DelFD(ns, db, tb, fd string) { - - t.del(_fd, tb) - -} diff --git a/txn/ft.go b/txn/ft.go deleted file mode 100644 index ac4942e5..00000000 --- a/txn/ft.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllFT(ctx context.Context, ns, db, tb string) (out []*sql.DefineTableStatement, err error) { - - if out, ok := t.get(_ft, tb); ok { - return out.([]*sql.DefineTableStatement), nil - } - - var kvs []kvs.KV - - key := &keys.FT{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb, FT: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineTableStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - t.set(_ft, tb, out) - - return - -} - -func (t *TX) DelFT(ns, db, tb, ft string) { - - t.del(_ft, tb) - -} diff --git a/txn/ix.go b/txn/ix.go deleted file mode 100644 index 87753f4d..00000000 --- a/txn/ix.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllIX(ctx context.Context, ns, db, tb string) (out []*sql.DefineIndexStatement, err error) { - - if out, ok := t.get(_ix, tb); ok { - return out.([]*sql.DefineIndexStatement), nil - } - - var kvs []kvs.KV - - key := &keys.IX{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb, IX: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineIndexStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - t.set(_ix, tb, out) - - return - -} - -func (t *TX) DelIX(ns, db, tb, ix string) { - - t.del(_ix, tb) - -} diff --git a/txn/lv.go b/txn/lv.go deleted file mode 100644 index 51c606b9..00000000 --- a/txn/lv.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllLV(ctx context.Context, ns, db, tb string) (out []*sql.LiveStatement, err error) { - - if out, ok := t.get(_lv, tb); ok { - return out.([]*sql.LiveStatement), nil - } - - var kvs []kvs.KV - - key := &keys.LV{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb, LV: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.LiveStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - t.set(_lv, tb, out) - - return - -} - -func (t *TX) DelLV(ns, db, tb, lv string) { - - t.del(_lv, tb) - -} diff --git a/txn/ns.go b/txn/ns.go deleted file mode 100644 index e78e0b84..00000000 --- a/txn/ns.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllNS(ctx context.Context) (out []*sql.DefineNamespaceStatement, err error) { - - var kvs []kvs.KV - - key := &keys.NS{KV: cnf.Settings.DB.Base, NS: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineNamespaceStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetNS(ctx context.Context, ns string) (val *sql.DefineNamespaceStatement, err error) { - - if out, ok := t.get(_ns, ns); ok { - return out.(*sql.DefineNamespaceStatement), nil - } - - var kv kvs.KV - - key := &keys.NS{KV: cnf.Settings.DB.Base, NS: ns} - - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorNSNotFound - } - - val = &sql.DefineNamespaceStatement{} - val.Decode(kv.Val()) - - t.set(_ns, ns, val) - - return - -} - -func (t *TX) AddNS(ctx context.Context, ns string) (val *sql.DefineNamespaceStatement, err error) { - - if out, ok := t.get(_ns, ns); ok { - return out.(*sql.DefineNamespaceStatement), nil - } - - var kv kvs.KV - - key := &keys.NS{KV: cnf.Settings.DB.Base, NS: ns} - - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return - } - - if kv != nil && kv.Exi() { - val = &sql.DefineNamespaceStatement{} - val.Decode(kv.Val()) - t.set(_ns, ns, val) - return - } - - val = &sql.DefineNamespaceStatement{Name: sql.NewIdent(ns)} - t.PutC(ctx, 0, key.Encode(), val.Encode(), nil) - - t.set(_ns, ns, val) - - return - -} - -func (t *TX) DelNS(ns string) { - - t.del(_ns, ns) - -} diff --git a/txn/nt.go b/txn/nt.go deleted file mode 100644 index 59b16fae..00000000 --- a/txn/nt.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllNT(ctx context.Context, ns string) (out []*sql.DefineTokenStatement, err error) { - - var kvs []kvs.KV - - key := &keys.NT{KV: cnf.Settings.DB.Base, NS: ns, TK: keys.Ignore} - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineTokenStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetNT(ctx context.Context, ns, tk string) (val *sql.DefineTokenStatement, err error) { - - var kv kvs.KV - - key := &keys.NT{KV: cnf.Settings.DB.Base, NS: ns, TK: tk} - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorNTNotFound - } - - val = &sql.DefineTokenStatement{} - val.Decode(kv.Val()) - - return - -} diff --git a/txn/nu.go b/txn/nu.go deleted file mode 100644 index 63b8d61b..00000000 --- a/txn/nu.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllNU(ctx context.Context, ns string) (out []*sql.DefineLoginStatement, err error) { - - var kvs []kvs.KV - - key := &keys.NU{KV: cnf.Settings.DB.Base, NS: ns, US: keys.Ignore} - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineLoginStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetNU(ctx context.Context, ns, us string) (val *sql.DefineLoginStatement, err error) { - - var kv kvs.KV - - key := &keys.NU{KV: cnf.Settings.DB.Base, NS: ns, US: us} - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorNUNotFound - } - - val = &sql.DefineLoginStatement{} - val.Decode(kv.Val()) - - return - -} diff --git a/txn/sc.go b/txn/sc.go deleted file mode 100644 index 8100ebb8..00000000 --- a/txn/sc.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllSC(ctx context.Context, ns, db string) (out []*sql.DefineScopeStatement, err error) { - - var kvs []kvs.KV - - key := &keys.SC{KV: cnf.Settings.DB.Base, NS: ns, DB: db, SC: keys.Ignore} - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineScopeStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetSC(ctx context.Context, ns, db, sc string) (val *sql.DefineScopeStatement, err error) { - - var kv kvs.KV - - key := &keys.SC{KV: cnf.Settings.DB.Base, NS: ns, DB: db, SC: sc} - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorSCNotFound - } - - val = &sql.DefineScopeStatement{} - val.Decode(kv.Val()) - - return - -} diff --git a/txn/st.go b/txn/st.go deleted file mode 100644 index 53b385a3..00000000 --- a/txn/st.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllST(ctx context.Context, ns, db, sc string) (out []*sql.DefineTokenStatement, err error) { - - var kvs []kvs.KV - - key := &keys.ST{KV: cnf.Settings.DB.Base, NS: ns, DB: db, SC: sc, TK: keys.Ignore} - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineTokenStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetST(ctx context.Context, ns, db, sc, tk string) (val *sql.DefineTokenStatement, err error) { - - var kv kvs.KV - - key := &keys.ST{KV: cnf.Settings.DB.Base, NS: ns, DB: db, SC: sc, TK: tk} - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorSTNotFound - } - - val = &sql.DefineTokenStatement{} - val.Decode(kv.Val()) - - return - -} diff --git a/txn/tb.go b/txn/tb.go deleted file mode 100644 index eff83cba..00000000 --- a/txn/tb.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "context" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/kvs" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/keys" -) - -func (t *TX) AllTB(ctx context.Context, ns, db string) (out []*sql.DefineTableStatement, err error) { - - var kvs []kvs.KV - - key := &keys.TB{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: keys.Ignore} - - if kvs, err = t.GetP(ctx, 0, key.Encode(), 0); err != nil { - return - } - - for _, kv := range kvs { - val := &sql.DefineTableStatement{} - val.Decode(kv.Val()) - out = append(out, val) - } - - return - -} - -func (t *TX) GetTB(ctx context.Context, ns, db, tb string) (val *sql.DefineTableStatement, err error) { - - if out, ok := t.get(_tb, tb); ok { - return out.(*sql.DefineTableStatement), nil - } - - var kv kvs.KV - - key := &keys.TB{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb} - - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return nil, err - } - - if !kv.Exi() { - return nil, ErrorTBNotFound - } - - val = &sql.DefineTableStatement{} - val.Decode(kv.Val()) - - t.set(_tb, tb, val) - - return - -} - -func (t *TX) AddTB(ctx context.Context, ns, db, tb string) (val *sql.DefineTableStatement, err error) { - - if out, ok := t.get(_tb, tb); ok { - return out.(*sql.DefineTableStatement), nil - } - - if _, err = t.AddDB(ctx, ns, db); err != nil { - return - } - - var kv kvs.KV - - key := &keys.TB{KV: cnf.Settings.DB.Base, NS: ns, DB: db, TB: tb} - - if kv, err = t.Get(ctx, 0, key.Encode()); err != nil { - return - } - - if kv != nil && kv.Exi() { - val = &sql.DefineTableStatement{} - val.Decode(kv.Val()) - t.set(_tb, tb, val) - return - } - - val = &sql.DefineTableStatement{Name: sql.NewIdent(tb)} - t.PutC(ctx, 0, key.Encode(), val.Encode(), nil) - - t.set(_tb, tb, val) - - return - -} - -func (t *TX) DelTB(ns, db, tb string) { - - t.del(_tb, tb) - -} diff --git a/txn/txn.go b/txn/txn.go deleted file mode 100644 index fad2d12f..00000000 --- a/txn/txn.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package txn - -import ( - "sync" - - "context" - - "github.com/surrealdb/surrealdb/kvs" -) - -type symbol int8 - -const ( - _ns symbol = iota - _db - _tb - _fd - _ix - _ev - _ft - _lv - _kv -) - -// -------------------------------------------------- - -type TX struct { - kvs.TX - lock sync.RWMutex - data map[symbol]map[string]interface{} -} - -func New(ctx context.Context, rw bool) (*TX, error) { - txn, err := kvs.Begin(ctx, rw) - if err != nil { - return nil, err - } - return &TX{TX: txn}, nil -} - -// -------------------------------------------------- - -func (t *TX) mem(s symbol) { - t.lock.Lock() - if t.data == nil { - t.data = make(map[symbol]map[string]interface{}, 8) - } - if t.data[s] == nil { - t.data[s] = make(map[string]interface{}, 5) - } - t.lock.Unlock() -} - -func (t *TX) del(s symbol, key string) { - t.mem(s) - t.lock.Lock() - delete(t.data[s], key) - t.lock.Unlock() -} - -func (t *TX) set(s symbol, key string, val interface{}) { - t.mem(s) - t.lock.Lock() - t.data[s][key] = val - t.lock.Unlock() -} - -func (t *TX) get(s symbol, key string) (val interface{}, ok bool) { - t.mem(s) - t.lock.RLock() - val, ok = t.data[s][key] - t.lock.RUnlock() - return -} diff --git a/util/build/build.go b/util/build/build.go deleted file mode 100644 index 9de346d0..00000000 --- a/util/build/build.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build - -import ( - "runtime" -) - -var ( - ver string // Version number - rev string // Git revision of this build - time string // Build time in UTC (year/month/day hour:min:sec) -) - -// Info holds information about the current build -type Info struct { - Go string `json:"go"` - Ver string `json:"ver"` - Rev string `json:"rev"` - Time string `json:"time"` -} - -// GetInfo returns information about the current build -func GetInfo() Info { - return Info{ - Go: runtime.Version(), - Ver: ver, - Rev: rev, - Time: time, - } -} diff --git a/util/comp/comp.go b/util/comp/comp.go deleted file mode 100644 index 16023980..00000000 --- a/util/comp/comp.go +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package comp - -import ( - "sort" - "strings" - "time" - - "golang.org/x/text/collate" - - "github.com/surrealdb/surrealdb/sql" -) - -func Comp(a, b interface{}, expr *sql.Order) int { - - switch x := a.(type) { - - case nil: - - switch b.(type) { - case nil: - return 0 - } - - case bool: - - switch y := b.(type) { - case nil: - return 1 - case bool: - if x == y { - return 0 - } else if !x && y { - return -1 - } else if x && !y { - return +1 - } - } - - case int64: - - switch y := b.(type) { - case nil, bool: - return 1 - case int64: - if x == y { - return 0 - } else if x < y { - return -1 - } else if x > y { - return +1 - } - case float64: - f := float64(x) - if f == y { - return 0 - } else if f < y { - return -1 - } else if f > y { - return +1 - } - } - - case float64: - - switch y := b.(type) { - case nil, bool: - return 1 - case int64: - f := float64(y) - if x == f { - return 0 - } else if x < f { - return -1 - } else if x > f { - return +1 - } - case float64: - if x == y { - return 0 - } else if x < y { - return -1 - } else if x > y { - return +1 - } - } - - case time.Time: - - switch y := b.(type) { - case nil, bool, int64, float64: - return 1 - case time.Time: - t1 := x.UTC().UnixNano() - t2 := y.UTC().UnixNano() - if t1 == t2 { - return 0 - } else if t1 < t2 { - return -1 - } else if t1 > t2 { - return +1 - } - } - - case string: - - switch y := b.(type) { - case nil, bool, int64, float64, time.Time: - return 1 - case string: - if expr.Tag.IsRoot() { - return strings.Compare(x, y) - } else { - c := collate.New( - expr.Tag, - collate.Loose, - collate.Force, - collate.OptionsFromTag(expr.Tag), - ) - return c.CompareString(x, y) - } - } - - case *sql.Thing: - - switch y := b.(type) { - case nil, bool, int64, float64, time.Time, string: - return 1 - case *sql.Thing: - if c := strings.Compare(x.TB, y.TB); c == 0 { - return Comp(x.ID, y.ID, expr) - } else { - return c - } - } - - case []interface{}: - - switch y := b.(type) { - case nil, bool, int64, float64, time.Time, string, *sql.Thing: - return 1 - case []interface{}: - - for i := 0; i < len(x) && i < len(y); i++ { - if c := Comp(x[i], y[i], expr); c != 0 { - return c - } - } - - return len(x) - len(y) - - } - - case map[string]interface{}: - - switch y := b.(type) { - case nil, bool, int64, float64, time.Time, string, *sql.Thing, []interface{}: - return 1 - case map[string]interface{}: - - var ke = make([]string, 0) - var me = make(map[string]bool) - - for k := range x { - if !me[k] { - me[k] = true - ke = append(ke, k) - } - } - for k := range y { - if !me[k] { - me[k] = true - ke = append(ke, k) - } - } - - sort.Strings(ke) - - for i := 0; i < len(x) && i < len(y); i++ { - k := ke[i] - if x[k] != nil && y[k] == nil { - return -1 - } - if x[k] == nil && y[k] != nil { - return 1 - } - if c := Comp(x[k], y[k], expr); c != 0 { - return c - } - } - - return len(x) - len(y) - - } - - } - - return -1 - -} diff --git a/util/conv/conv.go b/util/conv/conv.go deleted file mode 100644 index b68860ee..00000000 --- a/util/conv/conv.go +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package conv - -import ( - "fmt" - "strconv" - "time" - - "github.com/surrealdb/surrealdb/sql" -) - -func toNumber(str string) (float64, error) { - val, err := strconv.ParseFloat(str, 64) - if err != nil { - val = 0.0 - err = fmt.Errorf("Expected a number, but found '%v'", str) - - } - return float64(val), err -} - -func toBoolean(str string) (bool, error) { - val, err := strconv.ParseBool(str) - if err != nil { - val = false - err = fmt.Errorf("Expected a boolean, but found '%v'", str) - } - return bool(val), err -} - -// -------------------------------------------------- - -func MustBe(t, obj interface{}) (val interface{}) { - switch t { - default: - return obj - case "array": - return MustBeArray(obj) - case "object": - return MustBeObject(obj) - } -} - -func MustBeArray(obj interface{}) (val interface{}) { - if now, ok := obj.([]interface{}); ok { - val = now - } else { - val = make([]interface{}, 0) - } - return -} - -func MustBeObject(obj interface{}) (val interface{}) { - if now, ok := obj.(map[string]interface{}); ok { - val = now - } else { - val = make(map[string]interface{}) - } - return -} - -// -------------------------------------------------- - -func MightBe(obj interface{}) (val interface{}, ok bool) { - switch now := obj.(type) { - case string: - if val, ok := MightBeDatetime(now); ok { - return val, ok - } - if val, ok := MightBeRecord(now); ok { - return val, ok - } - } - return obj, false -} - -func MightBeDatetime(obj string) (val interface{}, ok bool) { - if val, err := time.Parse(time.RFC3339, obj); err == nil { - return val, true - } - return nil, false -} - -func MightBeRecord(obj string) (val interface{}, ok bool) { - if val := sql.ParseThing(obj); val != nil { - return val, true - } - return nil, false -} - -// -------------------------------------------------- - -func ConvertTo(t, k string, obj interface{}) (val interface{}, err error) { - switch t { - default: - return obj, nil - case "array": - return ConvertToArray(obj) - case "object": - return ConvertToObject(obj) - case "string": - return ConvertToString(obj) - case "number": - return ConvertToNumber(obj) - case "boolean": - return ConvertToBoolean(obj) - case "datetime": - return ConvertToDatetime(obj) - case "record": - return ConvertToRecord(obj, k) - } -} - -func ConvertToArray(obj interface{}) (val []interface{}, err error) { - if now, ok := obj.([]interface{}); ok { - val = now - } else { - err = fmt.Errorf("Expected an array, but found '%v'", obj) - } - return -} - -func ConvertToObject(obj interface{}) (val map[string]interface{}, err error) { - if now, ok := obj.(map[string]interface{}); ok { - val = now - } else { - err = fmt.Errorf("Expected an object, but found '%v'", obj) - } - return -} - -func ConvertToString(obj interface{}) (val string, err error) { - switch now := obj.(type) { - case string: - return now, err - case []interface{}, map[string]interface{}: - return val, fmt.Errorf("Expected a string, but found '%v'", obj) - default: - return fmt.Sprintf("%v", obj), err - } -} - -func ConvertToNumber(obj interface{}) (val float64, err error) { - switch now := obj.(type) { - case int64: - return float64(now), err - case float64: - return float64(now), err - case string: - return toNumber(now) - default: - return toNumber(fmt.Sprintf("%v", obj)) - } -} - -func ConvertToBoolean(obj interface{}) (val bool, err error) { - switch now := obj.(type) { - case int64: - return now > 0, err - case float64: - return now > 0, err - case string: - return toBoolean(now) - default: - return toBoolean(fmt.Sprintf("%v", obj)) - } -} - -func ConvertToDatetime(obj interface{}) (val time.Time, err error) { - switch now := obj.(type) { - case time.Time: - val = now - case string: - val, err = time.Parse(time.RFC3339Nano, now) - default: - err = fmt.Errorf("Expected a datetime, but found '%v'", obj) - } - return -} - -func ConvertToRecord(obj interface{}, tb string) (val *sql.Thing, err error) { - switch now := obj.(type) { - case *sql.Thing: - switch tb { - case now.TB: - val = now - case "": - val = now - default: - err = fmt.Errorf("Expected a record of type '%s', but found '%v'", tb, obj) - } - case string: - if val = sql.ParseThing(now); val == nil { - err = fmt.Errorf("Expected a record of type '%s', but found '%v'", tb, obj) - } - default: - switch tb { - default: - err = fmt.Errorf("Expected a record of type '%s', but found '%v'", tb, obj) - case "": - err = fmt.Errorf("Expected a record of any type, but found '%v'", obj) - } - } - return -} diff --git a/util/data/data.go b/util/data/data.go deleted file mode 100644 index 0b3dda5b..00000000 --- a/util/data/data.go +++ /dev/null @@ -1,1156 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package data - -import ( - "fmt" - "reflect" - "strconv" - "strings" - - "encoding/json" - - "github.com/surrealdb/surrealdb/util/dupe" - "github.com/surrealdb/surrealdb/util/pack" -) - -const ( - one int8 = iota - many -) - -const ( - choose int8 = iota - remove -) - -// Doc holds a reference to the core data object, or a selected path. -type Doc struct { - data interface{} -} - -// Fetcher is used when fetching values. -type Fetcher func(key string, val interface{}, path []string) interface{} - -// Iterator is used when iterating over items. -type Iterator func(key string, val interface{}) error - -// Walker is used when walking over items. -type Walker func(key string, val interface{}, exi bool) error - -// New creates a new data object. -func New() *Doc { - return &Doc{data: map[string]interface{}{}} -} - -// Consume converts a GO interface into a data object. -func Consume(input interface{}) *Doc { - return &Doc{data: input} -} - -// Data returns the internal data object as an interface. -func (d *Doc) Data() interface{} { - return d.data -} - -// Copy returns a duplicated copy of the internal data object. -func (d *Doc) Copy() *Doc { - return Consume(dupe.Duplicate(d.data)) -} - -// Encode encodes the data object to a byte slice. -func (d *Doc) Encode() (dst []byte) { - dst = pack.Encode(d.data) - return -} - -// Decode decodes the byte slice into a data object. -func (d *Doc) Decode(src []byte) *Doc { - pack.Decode(src, &d.data) - return d -} - -func (d *Doc) MarshalJSON() ([]byte, error) { - return json.Marshal(d.Data()) -} - -func (d *Doc) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &d.data) -} - -// -------------------------------------------------------------------------------- - -func (d *Doc) path(path ...string) (paths []string) { - - l := len(path) - for _, p := range path { - l += strings.Count(p, ".") - l += strings.Count(p, "[") - } - - paths = make([]string, 0, l) - - for _, p := range path { - for j, i, o := 0, 0, false; i < len(p); i++ { - switch { - case i == len(p)-1: - if len(p[j:]) > 0 { - paths = append(paths, p[j:]) - } - case p[i] == '.': - if len(p[j:i]) > 0 { - paths = append(paths, p[j:i]) - } - j, i = i+1, i+0 - case p[i] == '[': - if len(p[j:i]) > 0 { - paths = append(paths, p[j:i]) - } - j, i, o = i, i+1, true - case p[i] == ']' && o: - if len(p[j:i+1]) > 0 { - paths = append(paths, p[j:i+1]) - } - j, i, o = i+1, i+0, false - } - } - } - - return - -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func trim(s string) string { - if s[0] == '[' && s[len(s)-1] == ']' { - return s[1 : len(s)-1] - } - return s -} - -func (d *Doc) what(p string, a []interface{}, t int8) (o []interface{}, i []int, r int8) { - - p = trim(p) - - i = []int{} - - o = []interface{}{} - - // If there are no items in the - // original array, then return - // an empty array immediately. - - if len(a) == 0 { - if strings.ContainsAny(p, ":*") { - return o, i, many - } else { - return o, i, one - } - } - - // If the array index is a star - // or a colon only, then return - // the full array immediately - - if p == "*" || p == ":" { - switch t { - case choose: - for k := range a { - i = append(i, k) - } - return a, i, many - case remove: - for k := range a { - i = append(i, k) - } - return o, i, many - } - } - - // Split the specified array index - // by colons, so that we can get - // the specified array items. - - c := strings.Count(p, ":") - - if c == 0 { - - switch p { - case "0", "first": - if t == choose { - i = append(i, 0) - o = append(o, a[0]) - } else { - for k := range a[1:] { - i = append(i, k) - } - o = append(o, a[1:]...) - } - case "$", "last": - if t == choose { - i = append(i, len(a)-1) - o = append(o, a[len(a)-1]) - } else { - for k := range a[:len(a)-1] { - i = append(i, k) - } - o = append(o, a[:len(a)-1]...) - } - default: - if z, e := strconv.Atoi(p); e == nil { - if len(a) > z { - switch t { - case choose: - i = append(i, z) - o = append(o, a[z]) - case remove: - for k := range append(a[:z], a[z+1:]...) { - i = append(i, k) - } - o = append(o, append(a[:z], a[z+1:]...)...) - } - } else { - switch t { - case remove: - for k := range a { - i = append(i, k) - } - o = append(o, a[:]...) - } - } - } - } - - return o, i, one - - } - - if c == 1 { - - var e error - var s, f int - - b := []int{0, len(a)} - x := strings.Split(p, ":") - - for k := range x { - switch x[k] { - case "": - case "0", "first": - b[k] = 0 - case "$", "last": - b[k] = len(a) - default: - if b[k], e = strconv.Atoi(x[k]); e != nil { - return nil, nil, many - } - } - } - - s = b[0] - s = max(s, 0) - s = min(s, len(a)) - - f = b[1] - f = max(f, 0) - f = min(f, len(a)) - - if t == choose { - for k, v := range a[s:f] { - i = append(i, k) - o = append(o, v) - } - } else { - for k, v := range append(a[:s], a[f+1:]...) { - i = append(i, k) - o = append(o, v) - } - } - - return o, i, many - - } - - return nil, nil, many - -} - -// -------------------------------------------------------------------------------- - -// Reset empties and resets the data at the specified path. -func (d *Doc) Reset(path ...string) (*Doc, error) { - return d.Set(map[string]interface{}{}, path...) -} - -// Valid checks whether the value at the specified path is nil. -func (d *Doc) Valid(path ...string) bool { - if !d.Exists(path...) { - return false - } - return d.Get(path...).Data() != nil -} - -// Array sets the specified path to an array. -func (d *Doc) Array(path ...string) (*Doc, error) { - return d.Set([]interface{}{}, path...) -} - -// Object sets the specified path to an object. -func (d *Doc) Object(path ...string) (*Doc, error) { - return d.Set(map[string]interface{}{}, path...) -} - -// -------------------------------------------------------------------------------- - -// New sets the value at the specified path if it does not exist. -func (d *Doc) New(value interface{}, path ...string) (*Doc, error) { - if !d.Exists(path...) { - return d.Set(value, path...) - } - return d.Get(path...), nil -} - -// Iff sets the value at the specified path if it is not nil, or deletes it. -func (d *Doc) Iff(value interface{}, path ...string) (*Doc, error) { - if value != nil { - return d.Set(value, path...) - } - return &Doc{data: nil}, d.Del(path...) -} - -// Keys retrieves the object keys at the specified path. -func (d *Doc) Keys(path ...string) *Doc { - - path = d.path(path...) - - out := []interface{}{} - - if m, ok := d.Get(path...).Data().(map[string]interface{}); ok { - for k := range m { - out = append(out, k) - } - } - - return &Doc{data: out} - -} - -// Vals retrieves the object values at the specified path. -func (d *Doc) Vals(path ...string) *Doc { - - path = d.path(path...) - - out := []interface{}{} - - if m, ok := d.Get(path...).Data().(map[string]interface{}); ok { - for _, v := range m { - out = append(out, v) - } - } - - return &Doc{data: out} - -} - -// -------------------------------------------------------------------------------- - -// Exists checks whether the specified path exists. -func (d *Doc) Exists(path ...string) bool { - - path = d.path(path...) - - // If the value found at the current - // path part is undefined, then just - // return false immediately - - if d.data == nil { - return false - } - - // Define the temporary object so - // that we can loop over and traverse - // down the path parts of the data - - object := d.data - - // Loop over each part of the path - // whilst detecting if the data at - // the current path is an {} or [] - - for k, p := range path { - - p = trim(p) - - // If the value found at the current - // path part is an object, then move - // to the next part of the path - - if m, ok := object.(map[string]interface{}); ok { - if object, ok = m[p]; !ok { - return false - } - continue - } - - // If the value found at the current - // path part is an array, then perform - // the query on the specified items - - if a, ok := object.([]interface{}); ok { - - c, _, r := d.what(p, a, choose) - - if len(c) == 0 { - return false - } - - if r == one { - return Consume(c[0]).Exists(path[k+1:]...) - } - - if r == many { - for _, v := range c { - if !Consume(v).Exists(path[k+1:]...) { - return false - } - } - return true - } - - } - - return false - - } - - return true - -} - -// -------------------------------------------------------------------------------- - -// Get gets the value or values at a specified path. -func (d *Doc) Get(path ...string) *Doc { - return d.Fetch(nil, path...) -} - -// Fetch gets the value or values at a specified path, allowing for a custom fetch method. -func (d *Doc) Fetch(call Fetcher, path ...string) *Doc { - - path = d.path(path...) - - // If the value found at the current - // path part is undefined, then just - // return false immediately - - if d.data == nil { - return &Doc{data: nil} - } - - // Define the temporary object so - // that we can loop over and traverse - // down the path parts of the data - - object := d.data - - // Loop over each part of the path - // whilst detecting if the data at - // the current path is an {} or [] - - for k, p := range path { - - p = trim(p) - - // If the value found at the current - // path part is an object, then move - // to the next part of the path - - if m, ok := object.(map[string]interface{}); ok { - switch p { - default: - if call != nil { - object = call(p, m[p], path[k+1:]) - } else { - object = m[p] - } - case "*": - object = m - } - continue - } - - // If the value found at the current - // path part is an array, then perform - // the query on the specified items - - if a, ok := object.([]interface{}); ok { - - c, _, r := d.what(p, a, choose) - - if len(c) == 0 { - switch r { - case one: - return &Doc{data: nil} - case many: - return &Doc{data: []interface{}{}} - } - } - - if r == one { - if call != nil { - c[0] = call(p, c[0], path[k+1:]) - } - return Consume(c[0]).Fetch(call, path[k+1:]...) - } - - if r == many { - out := []interface{}{} - for _, v := range c { - if call != nil { - v = call(p, v, path[k+1:]) - } - res := Consume(v).Fetch(call, path[k+1:]...) - out = append(out, res.data) - } - return &Doc{data: out} - } - - } - - return &Doc{data: nil} - - } - - return &Doc{data: object} - -} - -// -------------------------------------------------------------------------------- - -// Set sets the value or values at a specified path. -func (d *Doc) Set(value interface{}, path ...string) (*Doc, error) { - - path = d.path(path...) - - if len(path) == 0 { - d.data = value - return d, nil - } - - // If the value found at the current - // path part is undefined, then ensure - // that it is an object - - if d.data == nil { - d.data = map[string]interface{}{} - } - - // Define the temporary object so - // that we can loop over and traverse - // down the path parts of the data - - object := d.data - - // Loop over each part of the path - // whilst detecting if the data at - // the current path is an {} or [] - - for k, p := range path { - - p = trim(p) - - // If the value found at the current - // path part is an object, then move - // to the next part of the path - - if m, ok := object.(map[string]interface{}); ok { - if k == len(path)-1 { - m[p] = value - } else if m[p] == nil { - m[p] = map[string]interface{}{} - } - object = m[p] - continue - } - - // If the value found at the current - // path part is an array, then perform - // the query on the specified items - - if a, ok := object.([]interface{}); ok { - - c, i, r := d.what(p, a, choose) - - if len(c) == 0 { - switch r { - case one: - return &Doc{data: nil}, nil - case many: - return &Doc{data: []interface{}{}}, nil - } - } - - if r == one { - if k == len(path)-1 { - a[i[0]] = value - object = a[i[0]] - continue - } else { - return Consume(a[i[0]]).Set(value, path[k+1:]...) - } - } - - if r == many { - out := []interface{}{} - for j, v := range c { - if k == len(path)-1 { - a[i[j]] = value - out = append(out, value) - } else { - res, _ := Consume(v).Set(value, path[k+1:]...) - if res.data != nil { - out = append(out, res.data) - } - } - } - return &Doc{data: out}, nil - } - - } - - } - - return &Doc{data: object}, nil - -} - -// -------------------------------------------------------------------------------- - -// Del deletes the value or values at a specified path. -func (d *Doc) Del(path ...string) error { - - path = d.path(path...) - - // If the value found at the current - // path part is undefined, then return - // a not an object error - - if d.data == nil { - return fmt.Errorf("Item is not an object") - } - - // Define the temporary object so - // that we can loop over and traverse - // down the path parts of the data - - object := d.data - - // Loop over each part of the path - // whilst detecting if the data at - // the current path is an {} or [] - - for k, p := range path { - - p = trim(p) - - // If the value found at the current - // path part is an object, then move - // to the next part of the path - - if m, ok := object.(map[string]interface{}); ok { - if k == len(path)-1 { - delete(m, p) - } else if m[p] == nil { - return fmt.Errorf("Item at path %s is not an object", path) - } - object = m[p] - continue - } - - // If the value found at the current - // path part is an array, then perform - // the query on the specified items - - if a, ok := object.([]interface{}); ok { - - var r int8 - var c []interface{} - - if k == len(path)-1 { - c, _, r = d.what(p, a, remove) - } else { - c, _, r = d.what(p, a, choose) - } - - if r == one { - if k == len(path)-1 { - d.Set(c, path[:len(path)-1]...) - continue - } else { - if len(c) != 0 { - return Consume(c[0]).Del(path[k+1:]...) - } - } - } - - if r == many { - if k == len(path)-1 { - d.Set(c, path[:len(path)-1]...) - continue - } else { - for _, v := range c { - Consume(v).Del(path[k+1:]...) - } - break - } - } - - } - - } - - return nil - -} - -// -------------------------------------------------------------------------------- - -// Append appends an item or an array of items to an array at the specified path. -func (d *Doc) Append(value interface{}, path ...string) (*Doc, error) { - - a, ok := d.Get(path...).Data().([]interface{}) - if !ok { - return &Doc{data: nil}, fmt.Errorf("Not an array") - } - - a = append(a, value) - - return d.Set(a, path...) - -} - -// ArrayAdd appends an item or an array of items to an array at the specified path. -func (d *Doc) ArrayAdd(value interface{}, path ...string) (*Doc, error) { - - a, ok := d.Get(path...).Data().([]interface{}) - if !ok { - return &Doc{data: nil}, fmt.Errorf("Not an array") - } - - if values, ok := value.([]interface{}); ok { - outer: - for _, value := range values { - for _, v := range a { - if reflect.DeepEqual(v, value) { - continue outer - } - } - a = append(a, value) - } - } else { - for _, v := range a { - if reflect.DeepEqual(v, value) { - return Consume(a), nil - } - } - a = append(a, value) - } - - return d.Set(a, path...) - -} - -// ArrayDel deletes an item or an array of items from an array at the specified path. -func (d *Doc) ArrayDel(value interface{}, path ...string) (*Doc, error) { - - a, ok := d.Get(path...).Data().([]interface{}) - if !ok { - return &Doc{data: nil}, fmt.Errorf("Not an array") - } - - if values, ok := value.([]interface{}); ok { - for _, value := range values { - for i := len(a) - 1; i >= 0; i-- { - v := a[i] - if reflect.DeepEqual(v, value) { - copy(a[i:], a[i+1:]) - a[len(a)-1] = nil - a = a[:len(a)-1] - } - } - } - } else { - for i := len(a) - 1; i >= 0; i-- { - v := a[i] - if reflect.DeepEqual(v, value) { - copy(a[i:], a[i+1:]) - a[len(a)-1] = nil - a = a[:len(a)-1] - } - } - } - - return d.Set(a, path...) - -} - -// -------------------------------------------------------------------------------- - -// Contains checks whether the value exists within the array at the specified path. -func (d *Doc) Contains(value interface{}, path ...string) bool { - - a, ok := d.Get(path...).Data().([]interface{}) - if !ok { - return false - } - - for _, v := range a { - if reflect.DeepEqual(v, value) { - return true - } - } - - return false - -} - -// -------------------------------------------------------------------------------- - -// Inc increments an item, or appends an item to an array at the specified path. -func (d *Doc) Inc(value interface{}, path ...string) (*Doc, error) { - - switch cur := d.Get(path...).Data().(type) { - case nil: - switch inc := value.(type) { - case int64: - return d.Set(0+inc, path...) - case float64: - return d.Set(0+inc, path...) - default: - switch value.(type) { - case []interface{}: - return d.Set(value, path...) - default: - return d.Set([]interface{}{value}, path...) - } - } - case int64: - switch inc := value.(type) { - case int64: - return d.Set(cur+inc, path...) - case float64: - return d.Set(float64(cur)+inc, path...) - } - case float64: - switch inc := value.(type) { - case int64: - return d.Set(cur+float64(inc), path...) - case float64: - return d.Set(cur+inc, path...) - } - case []interface{}: - return d.ArrayAdd(value, path...) - } - - return &Doc{data: nil}, fmt.Errorf("Not possible to increment.") - -} - -// Dec decrements an item, or removes an item from an array at the specified path. -func (d *Doc) Dec(value interface{}, path ...string) (*Doc, error) { - - switch cur := d.Get(path...).Data().(type) { - case nil: - switch inc := value.(type) { - case int64: - return d.Set(0-inc, path...) - case float64: - return d.Set(0-inc, path...) - } - case int64: - switch inc := value.(type) { - case int64: - return d.Set(cur-inc, path...) - case float64: - return d.Set(float64(cur)-inc, path...) - } - case float64: - switch inc := value.(type) { - case int64: - return d.Set(cur-float64(inc), path...) - case float64: - return d.Set(cur-inc, path...) - } - case []interface{}: - return d.ArrayDel(value, path...) - } - - return &Doc{data: nil}, fmt.Errorf("Not possible to decrement.") - -} - -// -------------------------------------------------------------------------------- - -func (d *Doc) Same(n *Doc) bool { - - switch a := d.data.(type) { - case []interface{}: - switch b := n.data.(type) { - case map[string]interface{}: - return false - case []interface{}: - if len(a) != len(b) { - return false - } - break - } - case map[string]interface{}: - switch b := n.data.(type) { - case []interface{}: - return false - case map[string]interface{}: - if len(a) != len(b) { - return false - } - break - } - } - - return reflect.DeepEqual(d, n) - -} - -func (d *Doc) Diff(n *Doc) map[string]interface{} { - - var initial = make(map[string]interface{}) - var current = make(map[string]interface{}) - var changes = make(map[string]interface{}) - - d.Each(func(key string, val interface{}) error { - initial[key] = val - return nil - }) - - n.Each(func(key string, val interface{}) error { - current[key] = val - return nil - }) - - for k, v := range current { - if o, ok := initial[k]; ok { - if reflect.DeepEqual(o, v) { - continue - } - } - changes[k] = v - } - - for k := range initial { - if _, ok := current[k]; !ok { - changes[k] = nil - } - } - - return changes - -} - -// -------------------------------------------------------------------------------- - -func (d *Doc) join(parts ...[]string) string { - var path []string - for _, part := range parts { - path = append(path, part...) - } - return strings.Join(path, ".") -} - -// -------------------------------------------------------------------------------- - -// Each loops through the values in the data doc. -func (d *Doc) Each(exec Iterator) error { - - return d.each(exec, nil) - -} - -func (d *Doc) each(exec Iterator, prev []string) error { - - // Define the temporary object so - // that we can loop over and traverse - // down the path parts of the data - - object := d.data - - // If the value found at the current - // path part is an object, then move - // to the next part of the path - - if m, ok := object.(map[string]interface{}); ok { - exec(d.join(prev), make(map[string]interface{})) - for k, v := range m { - var keep []string - keep = append(keep, prev...) - keep = append(keep, k) - Consume(v).each(exec, keep) - } - return nil - } - - // If the value found at the current - // path part is an array, then perform - // the query on the specified items - - if a, ok := object.([]interface{}); ok { - exec(d.join(prev), make([]interface{}, len(a))) - for i, v := range a { - var keep []string - keep = append(keep, prev...) - keep = append(keep, fmt.Sprintf("[%d]", i)) - Consume(v).each(exec, keep) - } - return nil - } - - return exec(d.join(prev), object) - -} - -// -------------------------------------------------------------------------------- - -// Walk walks the value or values at a specified path. -func (d *Doc) Walk(exec Walker, path ...string) error { - - path = d.path(path...) - - return d.walk(exec, nil, path...) - -} - -func (d *Doc) walk(exec Walker, prev []string, path ...string) error { - - if len(path) == 0 { - return nil - } - - // If the value found at the current - // path part is undefined, then ensure - // that it is an object - - if d.data == nil { - d.data = map[string]interface{}{} - } - - // Define the temporary object so - // that we can loop over and traverse - // down the path parts of the data - - object := d.data - - // Loop over each part of the path - // whilst detecting if the data at - // the current path is an {} or [] - - for k, p := range path { - - p = trim(p) - - // If the value found at the current - // path part is an object, then move - // to the next part of the path - - if m, ok := object.(map[string]interface{}); ok { - if object, ok = m[p]; !ok { - return exec(d.join(prev, path), nil, false) - } - continue - } - - // If the value found at the current - // path part is an array, then perform - // the query on the specified items - - if a, ok := object.([]interface{}); ok { - - c, i, r := d.what(p, a, choose) - - if r == one && len(c) == 0 { - return nil - } - - if r == one { - if k == len(path)-1 { - var keep []string - keep = append(keep, prev...) - keep = append(keep, path[:k]...) - keep = append(keep, fmt.Sprintf("[%d]", i[0])) - return exec(d.join(keep), c[0], true) - } else { - var keep []string - keep = append(keep, prev...) - keep = append(keep, path[:k]...) - keep = append(keep, fmt.Sprintf("[%d]", i[0])) - return Consume(c[0]).walk(exec, keep, path[k+1:]...) - } - } - - if r == many { - for j, v := range c { - if k == len(path)-1 { - var keep []string - keep = append(keep, prev...) - keep = append(keep, path[:k]...) - keep = append(keep, fmt.Sprintf("[%d]", i[j])) - if err := exec(d.join(keep), v, true); err != nil { - return err - } - } else { - var keep []string - keep = append(keep, prev...) - keep = append(keep, path[:k]...) - keep = append(keep, fmt.Sprintf("[%d]", i[j])) - if err := Consume(v).walk(exec, keep, path[k+1:]...); err != nil { - return err - } - } - } - return nil - } - - } - - // The current path item is not an object or an array - // but there are still other items in the search path. - - return nil - - } - - return exec(d.join(prev, path), object, true) - -} diff --git a/util/data/data_test.go b/util/data/data_test.go deleted file mode 100644 index bb91d364..00000000 --- a/util/data/data_test.go +++ /dev/null @@ -1,1092 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package data - -import ( - "errors" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestConversion(t *testing.T) { - - Convey("Can encode and decode", t, func() { - doc := Consume(map[string]interface{}{ - "bool": true, - "time": time.Now().UTC(), - }) - enc := doc.Encode() - dec := doc.Decode(enc) - So(doc, ShouldResemble, dec) - }) - -} - -func TestOperations(t *testing.T) { - - // ---------------------------------------------------------------------- - // Ability to set and del nil - // ---------------------------------------------------------------------- - - Convey("Can get nil", t, func() { - doc := Consume(nil) - So(doc, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Exists("nil"), ShouldBeFalse) - So(doc.Get("nil").Data(), ShouldEqual, nil) - }) - - Convey("Can set nil", t, func() { - doc := Consume(nil) - set, err := doc.Set("OK", "nil") - So(err, ShouldBeNil) - So(doc, ShouldHaveSameTypeAs, &Doc{}) - So(set.Data(), ShouldResemble, "OK") - So(doc.Get("nil").Data(), ShouldEqual, "OK") - }) - - Convey("Can't del nil", t, func() { - doc := Consume(nil) - err := doc.Del("nil") - So(err, ShouldNotBeNil) - }) - - Convey("Can't each nil", t, func() { - doc := Consume(nil) - var i int - doc.Each(func(key string, val interface{}) error { - i++ - return nil - }) - So(i, ShouldEqual, 1) - }) - - // ---------------------------------------------------------------------- - // Ability to attempt new() - // ---------------------------------------------------------------------- - - Convey("Can attempt to use New()", t, func() { - doc := New() - one, err := doc.New("OK", "item") - So(err, ShouldBeNil) - So(one.Data(), ShouldEqual, "OK") - So(doc.Exists("item"), ShouldBeTrue) - So(doc.Get("item").Data(), ShouldEqual, "OK") - two, err := doc.New("NOT OK", "item") - So(err, ShouldBeNil) - So(two.Data(), ShouldEqual, "OK") - So(doc.Exists("item"), ShouldBeTrue) - So(doc.Get("item").Data(), ShouldEqual, "OK") - }) - - // ---------------------------------------------------------------------- - // Ability to attempt iff() - // ---------------------------------------------------------------------- - - Convey("Can attempt to use Iff()", t, func() { - doc := New() - one, err := doc.Iff("OK", "item") - So(err, ShouldBeNil) - So(one.Data(), ShouldEqual, "OK") - So(doc.Exists("item"), ShouldBeTrue) - So(doc.Get("item").Data(), ShouldEqual, "OK") - two, err := doc.Iff(nil, "item") - So(err, ShouldBeNil) - So(two.Data(), ShouldEqual, nil) - So(doc.Exists("item"), ShouldBeFalse) - So(doc.Get("item").Data(), ShouldEqual, nil) - }) - - // ---------------------------------------------------------------------- - // Ability to set and get array - // ---------------------------------------------------------------------- - - Convey("Can set base array", t, func() { - doc := New() - obj, err := doc.Array("array") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("array").Data(), ShouldResemble, []interface{}{}) - }) - - // ---------------------------------------------------------------------- - // Ability to set and get object - // ---------------------------------------------------------------------- - - Convey("Can set base object", t, func() { - doc := New() - obj, err := doc.Object("object") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("object").Data(), ShouldResemble, map[string]interface{}{}) - }) - - // ---------------------------------------------------------------------- - // Ability to set and get basic types - // ---------------------------------------------------------------------- - - Convey("Can set and get basic number", t, func() { - doc := New() - obj, err := doc.Set(1, "number") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("number").Data(), ShouldResemble, 1) - }) - - Convey("Can set and get basic string", t, func() { - doc := New() - obj, err := doc.Set("a", "string") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("string").Data(), ShouldResemble, "a") - }) - - Convey("Can set and get basic array", t, func() { - doc := New() - obj, err := doc.Set([]interface{}{1, 2, 3}, "array") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("array").Data(), ShouldResemble, []interface{}{1, 2, 3}) - }) - - Convey("Can set and get basic object", t, func() { - doc := New() - obj, err := doc.Set(map[string]interface{}{"test": true}, "object") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("object").Data(), ShouldResemble, map[string]interface{}{"test": true}) - }) - - // ---------------------------------------------------------------------- - // Ability to set and get basic embedded types - // ---------------------------------------------------------------------- - - Convey("Can set and get basic embedded number", t, func() { - doc := New() - obj, err := doc.Set(1, "sub.number") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("sub.number").Data(), ShouldResemble, 1) - }) - - Convey("Can set and get basic embedded string", t, func() { - doc := New() - obj, err := doc.Set("a", "sub.string") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("sub.string").Data(), ShouldResemble, "a") - }) - - Convey("Can set and get basic embedded array", t, func() { - doc := New() - obj, err := doc.Set([]interface{}{1, 2, 3}, "sub.array") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("sub.array").Data(), ShouldResemble, []interface{}{1, 2, 3}) - }) - - Convey("Can set and get basic embedded object", t, func() { - doc := New() - obj, err := doc.Set(map[string]interface{}{"test": true}, "sub.object") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("sub.object").Data(), ShouldResemble, map[string]interface{}{"test": true}) - }) - - // ---------------------------------------------------------------------- - // Ability to inc and dec basic types - // ---------------------------------------------------------------------- - - Convey("Can inc basic number", t, func() { - doc := New() - obj, err := doc.Inc(int64(100), "number") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("number").Data(), ShouldResemble, int64(100)) - }) - - Convey("Can dec basic number", t, func() { - doc := New() - obj, err := doc.Dec(int64(100), "number") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("number").Data(), ShouldResemble, int64(-100)) - }) - - Convey("Can inc basic double", t, func() { - doc := New() - obj, err := doc.Inc(float64(100), "double") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("double").Data(), ShouldResemble, float64(100)) - }) - - Convey("Can dec basic double", t, func() { - doc := New() - obj, err := doc.Dec(float64(100), "double") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("double").Data(), ShouldResemble, float64(-100)) - }) - - // ---------------------------------------------------------------------------------------------------- - - doc := New() - - alt := map[string]interface{}{ - "bool": true, - "number": 12, - "string": "s", - "tags": []interface{}{ - "Hot", - }, - } - - obj := map[string]interface{}{ - "bool": true, - "number": 10, - "string": "s", - "tags": []interface{}{ - "Hot", - }, - "object": map[string]interface{}{ - "enabled": false, - }, - "emptys": []interface{}{}, - "arrays": []interface{}{ - map[string]interface{}{ - "id": 1, - "one": "one", - "selected": map[string]interface{}{ - "city": "London", - }, - "addresses": []interface{}{ - map[string]interface{}{ - "city": "London", - }, - map[string]interface{}{ - "city": "New York", - }, - }, - }, - map[string]interface{}{ - "id": 2, - "two": "two", - "selected": map[string]interface{}{ - "city": "Tonbridge", - }, - "addresses": []interface{}{ - map[string]interface{}{ - "city": "Paris", - }, - map[string]interface{}{ - "city": "Tonbridge", - }, - }, - }, - }, - } - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can set fetcher function", t, func() { - doc.Fetch(func(key string, val interface{}, path []string) interface{} { - return val - }) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can't del undefined", t, func() { - err := doc.Del("the.item") - So(err, ShouldNotBeNil) - }) - - Convey("Can set object", t, func() { - def, err := doc.Set(obj, "the.item") - So(err, ShouldBeNil) - So(def, ShouldHaveSameTypeAs, &Doc{}) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can iterate using each", t, func() { - var i int - doc.Each(func(key string, val interface{}) error { - i++ - return nil - }) - So(i, ShouldEqual, 32) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can diff two different docs", t, func() { - dif := doc.Diff(doc) - So(len(dif), ShouldEqual, 0) - }) - - Convey("Can diff two different docs", t, func() { - obj := New() - obj.Set(alt, "the.item") - dif := doc.Diff(obj) - So(len(dif), ShouldEqual, 25) - }) - - Convey("Can diff two different docs", t, func() { - obj := New() - obj.Set(alt, "the.item") - dif := obj.Diff(doc) - So(len(dif), ShouldEqual, 25) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Does unset item exist", t, func() { - So(doc.Exists("the.none"), ShouldBeFalse) - }) - - Convey("Does item exist", t, func() { - So(doc.Exists("the.item"), ShouldBeTrue) - }) - - Convey("Does unset array item exist", t, func() { - So(doc.Exists("the.item.emptys.0.id"), ShouldBeFalse) - }) - - Convey("Does unset multi array item exist", t, func() { - So(doc.Exists("the.item.emptys.*.id"), ShouldBeFalse) - }) - - Convey("Does array item exist", t, func() { - So(doc.Exists("the.item.arrays.0.id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays[0].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays.[0].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays.first.id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays[first].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays.[first].id"), ShouldBeTrue) - }) - - Convey("Does array item exist", t, func() { - So(doc.Exists("the.item.arrays.1.id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays[1].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays.[1].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays.last.id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays[last].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays.[last].id"), ShouldBeTrue) - }) - - Convey("Does out of bounds array item exist", t, func() { - So(doc.Exists("the.item.arrays.5.id"), ShouldBeFalse) - So(doc.Exists("the.item.arrays[5].id"), ShouldBeFalse) - }) - - Convey("Does unset array item exist", t, func() { - So(doc.Exists("the.item.arrays.0.none"), ShouldBeFalse) - So(doc.Exists("the.item.arrays[0].none"), ShouldBeFalse) - }) - - Convey("Does incorrectly embedded array item exist", t, func() { - So(doc.Exists("the.item.arrays.0.id.arggghh"), ShouldBeFalse) - So(doc.Exists("the.item.arrays[0].id.arggghh"), ShouldBeFalse) - }) - - Convey("Does incorrectly embedded object item exist", t, func() { - So(doc.Exists("the.item.object.enabled.arggghh"), ShouldBeFalse) - }) - - Convey("Does multi array item exist", t, func() { - So(doc.Exists("the.item.arrays.*.id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays[*].id"), ShouldBeTrue) - So(doc.Exists("the.item.arrays[:].id"), ShouldBeTrue) - }) - - Convey("Does sparse multi array item exist", t, func() { - So(doc.Exists("the.item.arrays.*.one"), ShouldBeFalse) - So(doc.Exists("the.item.arrays[*].one"), ShouldBeFalse) - So(doc.Exists("the.item.arrays[:].one"), ShouldBeFalse) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Is unset item valid", t, func() { - So(doc.Valid("the.none"), ShouldBeFalse) - }) - - Convey("Is item valid", t, func() { - So(doc.Valid("the.item"), ShouldBeTrue) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get object keys and vals", t, func() { - So(doc.Keys("the.item.object").Data(), ShouldResemble, []interface{}{"enabled"}) - So(doc.Vals("the.item.object").Data(), ShouldResemble, []interface{}{false}) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get unset item", t, func() { - So(doc.Get("the.item.none").Data(), ShouldResemble, nil) - So(doc.Get("the.item.none.arggghh").Data(), ShouldResemble, nil) - }) - - Convey("Can set unset item", t, func() { - set, err := doc.Set("OK", "the.item.none") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "OK") - So(doc.Get("the.item.none").Data(), ShouldResemble, "OK") - }) - - Convey("Can del unset item", t, func() { - err := doc.Del("the.item.none") - So(err, ShouldBeNil) - So(doc.Get("the.item.none").Data(), ShouldResemble, nil) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get basic bool", t, func() { - So(doc.Get("the.item.bool").Data(), ShouldBeTrue) - }) - - Convey("Can set basic bool", t, func() { - set, err := doc.Set(false, "the.item.bool") - So(err, ShouldBeNil) - So(set.Data(), ShouldBeFalse) - So(doc.Get("the.item.bool").Data(), ShouldBeFalse) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get basic number", t, func() { - So(doc.Get("the.item.number").Data(), ShouldResemble, 10) - }) - - Convey("Can set basic number", t, func() { - set, err := doc.Set(20, "the.item.number") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, 20) - So(doc.Get("the.item.number").Data(), ShouldResemble, 20) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get basic string", t, func() { - So(doc.Get("the.item.string").Data(), ShouldResemble, "s") - }) - - Convey("Can set basic string", t, func() { - set, err := doc.Set("t", "the.item.string") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "t") - So(doc.Get("the.item.string").Data(), ShouldResemble, "t") - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can inc += 1", t, func() { - obj, err := doc.Inc(int64(1), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, int64(1)) - }) - - Convey("Can inc += 4", t, func() { - obj, err := doc.Inc(int64(4), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, int64(5)) - }) - - Convey("Can inc += 3.87659", t, func() { - obj, err := doc.Inc(float64(3.87659), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(8.87659)) - }) - - Convey("Can inc += 1.12341", t, func() { - obj, err := doc.Inc(float64(1.12341), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(10)) - }) - - Convey("Can inc += 5", t, func() { - obj, err := doc.Inc(int64(5), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(15)) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can reset tester", t, func() { - obj, err := doc.Set(int64(15), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, int64(15)) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can dec -= 5", t, func() { - obj, err := doc.Dec(int64(5), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, int64(10)) - }) - - Convey("Can dec -= 1.12341", t, func() { - obj, err := doc.Dec(float64(1.12341), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(8.87659)) - }) - - Convey("Can dec -= 3.87659", t, func() { - obj, err := doc.Dec(float64(3.87659), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(5)) - }) - - Convey("Can dec -= 4", t, func() { - obj, err := doc.Dec(int64(4), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(1)) - }) - - Convey("Can dec -= 1", t, func() { - obj, err := doc.Dec(int64(1), "the.item.tester") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.tester").Data(), ShouldResemble, float64(0)) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can reset bool", t, func() { - obj, err := doc.Set(true, "the.item.bool") - So(err, ShouldBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.bool").Data(), ShouldBeTrue) - }) - - Convey("Can't inc non incable item", t, func() { - obj, err := doc.Inc(int64(1), "the.item.bool") - So(err, ShouldNotBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.bool").Data(), ShouldBeTrue) - }) - - Convey("Can't dec non decable item", t, func() { - obj, err := doc.Dec(int64(1), "the.item.bool") - So(err, ShouldNotBeNil) - So(obj, ShouldHaveSameTypeAs, &Doc{}) - So(doc.Get("the.item.bool").Data(), ShouldBeTrue) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get array", t, func() { - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot"}) - }) - - Convey("Can set array", t, func() { - set, err := doc.Set([]interface{}{"Hot", "Humid", "Sticky", "Warm"}, "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - }) - - Convey("Can see if array contains valid", t, func() { - So(doc.Contains("Hot", "the.item.tags"), ShouldBeTrue) - }) - - Convey("Can see if array contains invalid", t, func() { - So(doc.Contains("Cold", "the.item.tags"), ShouldBeFalse) - }) - - Convey("Can get range queries from array", t, func() { - So(doc.Get("the.item.tags[0:]").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - So(doc.Get("the.item.tags[:$]").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - So(doc.Get("the.item.tags[0:$]").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - So(doc.Get("the.item.tags[first:last]").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - So(doc.Get("the.item.tags[0:1]").Data(), ShouldResemble, []interface{}{"Hot"}) - So(doc.Get("the.item.tags[2:3]").Data(), ShouldResemble, []interface{}{"Sticky"}) - So(doc.Get("the.item.tags[2:4]").Data(), ShouldResemble, []interface{}{"Sticky", "Warm"}) - So(doc.Get("the.item.tags[2:5]").Data(), ShouldResemble, []interface{}{"Sticky", "Warm"}) - So(doc.Get("the.item.tags[2:9]").Data(), ShouldResemble, []interface{}{"Sticky", "Warm"}) - So(doc.Get("the.item.tags[4:5]").Data(), ShouldResemble, []interface{}{}) - So(doc.Get("the.item.tags[8:9]").Data(), ShouldResemble, []interface{}{}) - So(doc.Get("the.item.tags[0:none]").Data(), ShouldResemble, []interface{}{}) - So(doc.Get("the.item.tags[0:none:some]").Data(), ShouldResemble, []interface{}{}) - }) - - Convey("Can add single to array", t, func() { - _, err := doc.Inc("Sunny", "the.item.tags") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm", "Sunny"}) - }) - - Convey("Can add duplicate to array", t, func() { - _, err := doc.Inc("Sunny", "the.item.tags") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm", "Sunny"}) - }) - - Convey("Can add multiple to array", t, func() { - _, err := doc.Inc([]interface{}{"Sunny", "Snowy", "Icy"}, "the.item.tags") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm", "Sunny", "Snowy", "Icy"}) - }) - - Convey("Can del single from array", t, func() { - _, err := doc.Dec("Sunny", "the.item.tags") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm", "Snowy", "Icy"}) - }) - - Convey("Can del multiple from array", t, func() { - _, err := doc.Dec([]interface{}{"Snowy", "Icy"}, "the.item.tags") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - }) - - Convey("Can get array → *", t, func() { - So(doc.Get("the.item.tags.*").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm"}) - }) - - Convey("Can del array → 2", t, func() { - err := doc.Del("the.item.tags.2") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Warm"}) - }) - - Convey("Can't del array → 5", t, func() { - err := doc.Del("the.item.tags.5") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Warm"}) - }) - - Convey("Can set array → 0", t, func() { - set, err := doc.Set("Tepid", "the.item.tags.0") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "Tepid") - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Tepid", "Humid", "Warm"}) - }) - - Convey("Can't set array → 5", t, func() { - set, err := doc.Set("Other", "the.item.tags.5") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, nil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Tepid", "Humid", "Warm"}) - }) - - Convey("Can set array → first", t, func() { - set, err := doc.Set("Test1", "the.item.tags.first") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "Test1") - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Test1", "Humid", "Warm"}) - So(doc.Get("the.item.tags.0").Data(), ShouldResemble, doc.Get("the.item.tags.first").Data()) - }) - - Convey("Can set array → last", t, func() { - set, err := doc.Set("Test2", "the.item.tags.last") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "Test2") - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Test1", "Humid", "Test2"}) - So(doc.Get("the.item.tags.2").Data(), ShouldResemble, doc.Get("the.item.tags.last").Data()) - }) - - Convey("Can del array → first", t, func() { - err := doc.Del("the.item.tags.first") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Humid", "Test2"}) - So(doc.Get("the.item.tags.0").Data(), ShouldResemble, doc.Get("the.item.tags.first").Data()) - }) - - Convey("Can del array → last", t, func() { - err := doc.Del("the.item.tags.last") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Humid"}) - So(doc.Get("the.item.tags.0").Data(), ShouldResemble, doc.Get("the.item.tags.last").Data()) - }) - - Convey("Can set array → *", t, func() { - set, err := doc.Set("Unknown", "the.item.tags.*") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, []interface{}{"Unknown"}) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Unknown"}) - }) - - Convey("Can del array → *", t, func() { - err := doc.Del("the.item.tags.*") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{}) - }) - - Convey("Can del single from array", t, func() { - _, err := doc.Inc([]interface{}{"Hot", "Humid", "Sticky", "Warm", "Snowy", "Icy"}, "the.item.tags") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Hot", "Humid", "Sticky", "Warm", "Snowy", "Icy"}) - }) - - Convey("Can del single from array", t, func() { - err := doc.Del("the.item.tags[0:3]") - So(err, ShouldBeNil) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy"}) - }) - - Convey("Can add to array", t, func() { - set, err := doc.ArrayAdd("None", "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldHaveLength, 3) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy", "None"}) - }) - - Convey("Can add to array", t, func() { - set, err := doc.ArrayAdd("None", "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldHaveLength, 3) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy", "None"}) - }) - - Convey("Can del from array", t, func() { - set, err := doc.ArrayDel("None", "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldHaveLength, 2) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy"}) - }) - - Convey("Can append to array", t, func() { - set, err := doc.Append("None", "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldHaveLength, 3) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy", "None"}) - }) - - Convey("Can append to array", t, func() { - set, err := doc.Append("None", "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldHaveLength, 4) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy", "None", "None"}) - }) - - Convey("Can append to array", t, func() { - set, err := doc.Append("None", "the.item.tags") - So(err, ShouldBeNil) - So(set.Data(), ShouldHaveLength, 5) - So(doc.Get("the.item.tags").Data(), ShouldResemble, []interface{}{"Snowy", "Icy", "None", "None", "None"}) - }) - - Convey("Can del array", t, func() { - err := doc.Del("the.item.tags") - So(err, ShouldBeNil) - }) - - Convey("Can't add to not array", t, func() { - _, err := doc.ArrayAdd("None", "the.item.tags") - So(err, ShouldNotBeNil) - }) - - Convey("Can't del from not array", t, func() { - _, err := doc.ArrayDel("None", "the.item.tags") - So(err, ShouldNotBeNil) - }) - - Convey("Can't see if array contains", t, func() { - So(doc.Contains("None", "the.item.tags"), ShouldBeFalse) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get object → key", t, func() { - So(doc.Get("the.item.object.enabled").Data(), ShouldBeFalse) - }) - - Convey("Can set object → key", t, func() { - set, err := doc.Set(true, "the.item.object.enabled") - So(err, ShouldBeNil) - So(set.Data(), ShouldBeTrue) - So(doc.Get("the.item.object.enabled").Data(), ShouldBeTrue) - }) - - Convey("Can del object → key", t, func() { - err := doc.Del("the.item.object.enabled") - So(err, ShouldBeNil) - So(doc.Exists("the.item.object.enabled"), ShouldBeFalse) - So(doc.Get("the.item.object.enabled").Data(), ShouldResemble, nil) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get array → * → key", t, func() { - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{1, 2}) - }) - - Convey("Can't get array → 5 → key", t, func() { - So(doc.Get("the.item.arrays.5.id").Data(), ShouldResemble, nil) - }) - - Convey("Can set array → * → key", t, func() { - set, err := doc.Set("ID", "the.item.arrays.*.id") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, []interface{}{"ID", "ID"}) - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{"ID", "ID"}) - }) - - Convey("Can set array → 0 → key", t, func() { - set, err := doc.Set("ID1", "the.item.arrays.0.id") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "ID1") - So(doc.Get("the.item.arrays.0.id").Data(), ShouldResemble, "ID1") - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{"ID1", "ID"}) - }) - - Convey("Can set array → 1 → key", t, func() { - set, err := doc.Set("ID2", "the.item.arrays.1.id") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, "ID2") - So(doc.Get("the.item.arrays.1.id").Data(), ShouldResemble, "ID2") - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{"ID1", "ID2"}) - }) - - Convey("Can del array → 0 → key", t, func() { - err := doc.Del("the.item.arrays.0.id") - So(err, ShouldBeNil) - So(doc.Get("the.item.arrays.0.id").Data(), ShouldResemble, nil) - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{nil, "ID2"}) - }) - - Convey("Can't del array → 5 → key", t, func() { - err := doc.Del("the.item.arrays.5.id") - So(err, ShouldBeNil) - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{nil, "ID2"}) - }) - - Convey("Can del array → * → key", t, func() { - err := doc.Del("the.item.arrays.*.id") - So(err, ShouldBeNil) - So(doc.Get("the.item.arrays.0.id").Data(), ShouldResemble, nil) - So(doc.Get("the.item.arrays.*.id").Data(), ShouldResemble, []interface{}{nil, nil}) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get object → key", t, func() { - So(doc.Get("the.item.arrays.*.one").Data(), ShouldResemble, []interface{}{"one", nil}) - }) - - Convey("Can get object → key", t, func() { - So(doc.Get("the.item.arrays.*.two").Data(), ShouldResemble, []interface{}{nil, "two"}) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can get array → * → object → !", t, func() { - So(doc.Get("the.item.arrays.*.selected.none").Data(), ShouldResemble, []interface{}{nil, nil}) - }) - - Convey("Can set array → * → object → !", t, func() { - set, err := doc.Set("OK", "the.item.arrays.*.selected.none") - So(err, ShouldBeNil) - So(set.Data(), ShouldResemble, []interface{}{"OK", "OK"}) - So(doc.Get("the.item.arrays.*.selected.none").Data(), ShouldResemble, []interface{}{"OK", "OK"}) - }) - - Convey("Can get array → * → object → key", t, func() { - So(doc.Get("the.item.arrays[*].selected.city").Data(), ShouldResemble, []interface{}{"London", "Tonbridge"}) - So(doc.Get("the.item.arrays[:].selected.city").Data(), ShouldResemble, []interface{}{"London", "Tonbridge"}) - }) - - Convey("Can get array → 0 → arrays → 0 → key", t, func() { - So(doc.Get("the.item.arrays.0.addresses.0.city").Data(), ShouldResemble, "London") - So(doc.Get("the.item.arrays.0.addresses.0.city").Data(), ShouldResemble, "London") - }) - - Convey("Can get array → * → arrays → 0 → key", t, func() { - So(doc.Get("the.item.arrays.*.addresses.0.city").Data(), ShouldResemble, []interface{}{"London", "Paris"}) - }) - - Convey("Can get array → * → arrays → * → key", t, func() { - So(doc.Get("the.item.arrays.*.addresses.*.city").Data(), ShouldResemble, []interface{}{[]interface{}{"London", "New York"}, []interface{}{"Paris", "Tonbridge"}}) - }) - - Convey("Can get array → ! → arrays → 0 → key", t, func() { - So(doc.Get("the.item.arrays.5.addresses.0.city").Data(), ShouldResemble, nil) - }) - - // ---------------------------------------------------------------------------------------------------- - - tmp := []interface{}{ - map[string]interface{}{ - "test": "one", - }, - map[string]interface{}{ - "test": "two", - }, - map[string]interface{}{ - "test": "tre", - }, - } - - Convey("Can del array", t, func() { - err := doc.Del("the.item.arrays") - So(err, ShouldBeNil) - }) - - Convey("Can walk nil", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - doc.Set(tmp, "none") - So(exi, ShouldBeTrue) - return nil - }) - So(doc.Exists("none"), ShouldBeFalse) - }) - - Convey("Can walk array", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldResemble, "the.item.arrays") - So(exi, ShouldBeFalse) - doc.Set(tmp, key) - return nil - }, "the.item.arrays") - So(doc.Get("the.item.arrays").Data(), ShouldResemble, tmp) - }) - - Convey("Can walk array → *", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldBeIn, "the.item.arrays.[0]", "the.item.arrays.[1]", "the.item.arrays.[2]") - So(val, ShouldBeIn, tmp[0], tmp[1], tmp[2]) - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.*") - }) - - Convey("Can walk array → * → object", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldBeIn, "the.item.arrays.[0].test", "the.item.arrays.[1].test", "the.item.arrays.[2].test") - So(val, ShouldBeIn, "one", "two", "tre") - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.*.test") - }) - - Convey("Can walk array → first → object", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldResemble, "the.item.arrays.[0].test") - So(val, ShouldResemble, "one") - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.first.test") - }) - - Convey("Can walk array → last → object", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldResemble, "the.item.arrays.[2].test") - So(val, ShouldResemble, "tre") - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.last.test") - }) - - Convey("Can walk array → 0 → value", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldResemble, "the.item.arrays.[0]") - So(val, ShouldResemble, map[string]interface{}{"test": "one"}) - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.0") - }) - - Convey("Can walk array → 1 → value", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldResemble, "the.item.arrays.[1]") - So(val, ShouldResemble, map[string]interface{}{"test": "two"}) - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.1") - }) - - Convey("Can walk array → 2 → value", t, func() { - doc.Walk(func(key string, val interface{}, exi bool) error { - So(key, ShouldResemble, "the.item.arrays.[2]") - So(val, ShouldResemble, map[string]interface{}{"test": "tre"}) - So(exi, ShouldBeTrue) - return nil - }, "the.item.arrays.2") - }) - - Convey("Can walk array → 3 → value", t, func() { - err := doc.Walk(func(key string, val interface{}, exi bool) error { - return nil - }, "the.item.arrays.3") - So(err, ShouldBeNil) - }) - - Convey("Can walk array → 0 → value → value", t, func() { - err := doc.Walk(func(key string, val interface{}, exi bool) error { - return nil - }, "the.item.arrays.0.test.value") - So(err, ShouldBeNil) - }) - - Convey("Can walk array → 0 → value → value → value", t, func() { - err := doc.Walk(func(key string, val interface{}, exi bool) error { - return nil - }, "the.item.arrays.0.test.value.value") - So(err, ShouldBeNil) - }) - - Convey("Can force error from walk", t, func() { - err := doc.Walk(func(key string, val interface{}, exi bool) error { - return errors.New("Testing") - }, "the.item.something") - So(err, ShouldNotBeNil) - }) - - Convey("Can force error from walk array → *", t, func() { - err := doc.Walk(func(key string, val interface{}, exi bool) error { - return errors.New("Testing") - }, "the.item.arrays.*") - So(err, ShouldNotBeNil) - }) - - Convey("Can force error from walk array → * → value", t, func() { - err := doc.Walk(func(key string, val interface{}, exi bool) error { - return errors.New("Testing") - }, "the.item.arrays.*.test") - So(err, ShouldNotBeNil) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can copy object", t, func() { - So(doc.Copy().Data(), ShouldResemble, doc.Data()) - }) - - // ---------------------------------------------------------------------------------------------------- - - Convey("Can reset object", t, func() { - _, err := doc.Reset() - So(err, ShouldBeNil) - }) - -} diff --git a/util/deep/deep.go b/util/deep/deep.go deleted file mode 100644 index 74db683d..00000000 --- a/util/deep/deep.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package deep - -import ( - "time" - - "reflect" -) - -// Copy returns a deep copy of the source object. -func Copy(src interface{}) interface{} { - - if src == nil { - return nil - } - - prime := reflect.ValueOf(src) - - clone := reflect.New(prime.Type()).Elem() - - copy(prime, clone) - - return clone.Interface() - -} - -func copy(prime, clone reflect.Value) { - - switch prime.Kind() { - - case reflect.Ptr: - value := prime.Elem() - if !value.IsValid() { - return - } - clone.Set(reflect.New(value.Type())) - copy(value, clone.Elem()) - - case reflect.Interface: - if prime.IsNil() { - return - } - value := prime.Elem() - alike := reflect.New(value.Type()).Elem() - copy(value, alike) - clone.Set(alike) - - case reflect.Struct: - t, ok := prime.Interface().(time.Time) - if ok { - clone.Set(reflect.ValueOf(t)) - return - } - for i := 0; i < prime.NumField(); i++ { - if prime.Type().Field(i).PkgPath != "" { - continue - } - copy(prime.Field(i), clone.Field(i)) - } - - case reflect.Slice: - clone.Set(reflect.MakeSlice(prime.Type(), prime.Len(), prime.Cap())) - for i := 0; i < prime.Len(); i++ { - copy(prime.Index(i), clone.Index(i)) - } - - case reflect.Map: - clone.Set(reflect.MakeMap(prime.Type())) - for _, key := range prime.MapKeys() { - value := prime.MapIndex(key) - alike := reflect.New(value.Type()).Elem() - copy(value, alike) - clone.SetMapIndex(key, alike) - } - - default: - clone.Set(prime) - - } - -} diff --git a/util/deep/deep_test.go b/util/deep/deep_test.go deleted file mode 100644 index 9d08e56f..00000000 --- a/util/deep/deep_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package deep - -import ( - "time" - - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -type Mini struct { - embedded bool -} - -type Test struct { - PublicNumber int - PublicString string - PublicStruct interface{} - PublicPointr interface{} - PublicSlice []interface{} - PublicMap map[string]interface{} - privateNumber int - privateString string - privateStruct interface{} - privatePointr interface{} - privateSlice []interface{} - privateMap map[string]interface{} -} - -func TestMain(t *testing.T) { - - Convey("Can copy nil", t, func() { - var item interface{} - item = nil - done := Copy(item) - So(done, ShouldResemble, item) - }) - -} - -func TestSimple(t *testing.T) { - - Convey("Can copy bool", t, func() { - item := true - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy int64", t, func() { - item := int64(1) - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy float64", t, func() { - item := float64(1) - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy string", t, func() { - item := "string" - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy time.Time", t, func() { - item := time.Now() - done := Copy(item) - So(done, ShouldResemble, item) - }) - -} - -func TestSlices(t *testing.T) { - - Convey("Can copy slice of bools", t, func() { - item := []bool{ - true, - false, - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy slice of int64s", t, func() { - item := []int64{ - 1, - 2, - 3, - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy slice of float64s", t, func() { - item := []float64{ - 1, - 2, - 3, - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy slice of strings", t, func() { - item := []string{ - "str", - "str", - "str", - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy slice of time.Times", t, func() { - item := []time.Time{ - time.Now(), - time.Now(), - time.Now(), - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy slice of interfaces", t, func() { - item := []interface{}{ - nil, - int64(1), - float64(2), - "str", - time.Now(), - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - -} - -func TestObjects(t *testing.T) { - - Convey("Can copy map of bools", t, func() { - item := map[string]bool{ - "a": true, - "b": false, - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy map of int64s", t, func() { - item := map[string]int64{ - "a": 1, - "b": 2, - "c": 3, - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy map of float64s", t, func() { - item := map[string]float64{ - "a": 1, - "b": 2, - "c": 3, - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy map of strings", t, func() { - item := map[string]string{ - "a": "str", - "b": "str", - "c": "str", - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy map of time.Times", t, func() { - item := map[string]time.Time{ - "a": time.Now(), - "b": time.Now(), - "c": time.Now(), - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - - Convey("Can copy map of interfaces", t, func() { - item := map[interface{}]interface{}{ - 1: nil, - "b": int64(1), - true: float64(2), - "d": "str", - "e": time.Now(), - } - done := Copy(item) - So(done, ShouldResemble, item) - }) - -} - -func TestStructs(t *testing.T) { - - full := Test{ - PublicNumber: 1, - PublicString: "str", - PublicStruct: Mini{}, - PublicPointr: &Mini{}, - PublicSlice: []interface{}{nil, 1, "str", true}, - PublicMap: map[string]interface{}{ - "a": 1, - "b": "str", - "c": true, - "d": time.Now(), - }, - privateNumber: 1, - privateString: "str", - privateStruct: Mini{}, - privatePointr: &Mini{}, - privateSlice: []interface{}{nil, 1, "str", true}, - privateMap: map[string]interface{}{ - "a": 1, - "b": "str", - "c": true, - "d": time.Now(), - }, - } - - show := Test{ - PublicNumber: full.PublicNumber, - PublicString: full.PublicString, - PublicStruct: full.PublicStruct, - PublicPointr: full.PublicPointr, - PublicSlice: full.PublicSlice, - PublicMap: full.PublicMap, - } - - Convey("Can copy struct", t, func() { - item := full - done := Copy(item) - So(show, ShouldResemble, done) - }) - - Convey("Can copy pointer", t, func() { - item := &full - done := Copy(item) - So(&show, ShouldResemble, done) - }) - - Convey("Can copy slice of structs", t, func() { - item := []interface{}{full, full} - done := Copy(item) - So([]interface{}{show, show}, ShouldResemble, done) - }) - - Convey("Can copy slice of pointers", t, func() { - item := []interface{}{&full, &full} - done := Copy(item) - So([]interface{}{&show, &show}, ShouldResemble, done) - }) - -} diff --git a/util/diff/diff.go b/util/diff/diff.go deleted file mode 100644 index bce80422..00000000 --- a/util/diff/diff.go +++ /dev/null @@ -1,345 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package diff - -import ( - "fmt" - - "reflect" - "sort" - "strconv" - "strings" - - "github.com/surrealdb/surrealdb/sql" - - "github.com/surrealdb/surrealdb/util/data" - - "github.com/sergi/go-diff/diffmatchpatch" -) - -type operations struct { - ops []*operation -} - -type operation struct { - op string - from string - path string - value interface{} - before interface{} -} - -func Diff(old, now map[string]interface{}) []interface{} { - out := &operations{} - out.diff(old, now, "") - return out.diffs() -} - -func Patch(old map[string]interface{}, ops []interface{}) map[string]interface{} { - out := &operations{} - out.load(ops) - return out.patch(old) -} - -func (o *operations) load(ops []interface{}) { - - for _, v := range ops { - - if obj, ok := v.(map[string]interface{}); ok { - - op := &operation{} - - op.value = obj["value"] - - if str, ok := obj["op"].(string); ok { - op.op = str - } - - if str, ok := obj["from"].(string); ok { - op.from = str - } - - if str, ok := obj["path"].(string); ok { - op.path = str - } - - o.ops = append(o.ops, op) - - } - - } - -} - -func (o *operations) diffs() (ops []interface{}) { - - ops = make([]interface{}, len(o.ops)) - - sort.Slice(o.ops, func(i, j int) bool { - return o.ops[i].path < o.ops[j].path - }) - - for k, v := range o.ops { - - op := make(map[string]interface{}) - - if len(v.op) > 0 { - op["op"] = v.op - } - - if len(v.from) > 0 { - op["from"] = v.from - } - - if len(v.path) > 0 { - op["path"] = v.path - } - - if v.value != nil { - op["value"] = v.value - } - - ops[k] = op - - } - - return - -} - -func isIn(a int, list []int) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} - -func route(path string, part string) string { - if len(path) == 0 { - return "/" + part - } else { - if part[0] == '/' { - return path + part - } else { - return path + "/" + part - } - } -} - -func (o *operations) op(op, from, path string, before, after interface{}) { - - o.ops = append(o.ops, &operation{ - op: op, - from: from, - path: path, - value: after, - before: before, - }) - -} - -func (o *operations) diff(old, now map[string]interface{}, path string) { - - for key, after := range now { - - p := route(path, key) - - // Check if the value existed - before, ok := old[key] - - // Value did not previously exist - if !ok { - o.op("add", "", p, nil, after) - continue - } - - // Data type is now completely different - if reflect.TypeOf(after) != reflect.TypeOf(before) { - o.op("replace", "", p, before, after) - continue - } - - // Check whether the values have changed - o.vals(before, after, p) - - } - - for key, before := range old { - - p := route(path, key) - - // Check if the value exists - after, ok := now[key] - - // Value now no longer exists - if !ok { - o.op("remove", "", p, before, after) - continue - } - - } - - var used []int - - for i := len(o.ops) - 1; i >= 0; i-- { - if iv := o.ops[i]; !isIn(i, used) && iv.op == "add" { - for j := len(o.ops) - 1; j >= 0; j-- { - if jv := o.ops[j]; !isIn(j, used) && jv.op == "remove" { - if reflect.DeepEqual(iv.value, jv.before) { - used = append(used, []int{i, j}...) - o.op("move", jv.path, iv.path, nil, nil) - } - } - } - } - } - - sort.Sort(sort.Reverse(sort.IntSlice(used))) - - for _, i := range used { - o.ops = append(o.ops[:i], o.ops[i+1:]...) - } - -} - -func (o *operations) patch(old map[string]interface{}) (now map[string]interface{}) { - - obj := data.Consume(old) - - for _, v := range o.ops { - - path := strings.Split(v.path, "/") - - prev := path[:len(path)-1] - - switch v.op { - case "add": - switch obj.Get(prev...).Data().(type) { - case []interface{}: - obj.Append(v.value, prev...) - default: - obj.Set(v.value, path...) - } - case "remove": - obj.Del(path...) - case "replace": - obj.Set(v.value, path...) - case "change": - switch val := obj.Get(path...).Data().(type) { - case fmt.Stringer: - txt := val.String() - dmp := diffmatchpatch.New() - if pch, err := dmp.PatchFromText(v.value.(string)); err == nil { - txt, _ := dmp.PatchApply(pch, txt) - obj.Set(txt, path...) - } - case string: - dmp := diffmatchpatch.New() - if pch, err := dmp.PatchFromText(v.value.(string)); err == nil { - txt, _ := dmp.PatchApply(pch, val) - obj.Set(txt, path...) - } - - } - } - - } - - return old - -} - -func (o *operations) text(old, now string, path string) { - - dmp := diffmatchpatch.New() - - pch := dmp.PatchMake(old, now) - - txt := dmp.PatchToText(pch) - - o.op("change", "", path, old, txt) - -} - -func (o *operations) vals(old, now interface{}, path string) { - - if reflect.TypeOf(old) != reflect.TypeOf(now) { - o.op("replace", "", path, old, now) - return - } - - switch ov := old.(type) { - default: - if !reflect.DeepEqual(old, now) { - o.op("replace", "", path, old, now) - } - case *sql.Thing: - nv := now.(*sql.Thing) - if ov.TB != nv.TB || ov.ID != nv.ID { - o.op("replace", "", path, old, now) - } - case bool: - if ov != now.(bool) { - o.op("replace", "", path, old, now) - } - case int64: - if ov != now.(int64) { - o.op("replace", "", path, old, now) - } - case float64: - if ov != now.(float64) { - o.op("replace", "", path, old, now) - } - case string: - if ov != now.(string) { - o.text(ov, now.(string), path) - } - case nil: - switch now.(type) { - case nil: - default: - o.op("replace", "", path, old, now) - } - case map[string]interface{}: - o.diff(ov, now.(map[string]interface{}), path) - case []interface{}: - o.arrs(ov, now.([]interface{}), path) - } - -} - -func (o *operations) arrs(old, now []interface{}, path string) { - - var i int - - for i = 0; i < len(old) && i < len(now); i++ { - o.vals(old[i], now[i], route(path, strconv.Itoa(i))) - } - - for j := i; j < len(now); j++ { - if j >= len(old) || !reflect.DeepEqual(now[j], old[j]) { - o.op("add", "", route(path, strconv.Itoa(j)), nil, now[j]) - } - } - - for j := i; j < len(old); j++ { - if j >= len(now) || !reflect.DeepEqual(old[j], now[j]) { - o.op("remove", "", route(path, strconv.Itoa(j)), old[j], nil) - } - } - -} diff --git a/util/diff/diff_test.go b/util/diff/diff_test.go deleted file mode 100644 index 135bc60f..00000000 --- a/util/diff/diff_test.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package diff - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - - . "github.com/smartystreets/goconvey/convey" -) - -var old = map[string]interface{}{ - "age": 18, - "item": sql.NewThing("test", 1), - "name": map[string]interface{}{ - "first": "T", - "last": "M H", - }, - "dates": []interface{}{1, 2, 4}, - "changing": true, - "different": "true", -} - -var now = map[string]interface{}{ - "age": 29, - "item": sql.NewThing("test", 2), - "name": map[string]interface{}{ - "first": "Tobie", - "last": "Morgan Hitchcock", - }, - "changed": "This is a string", - "different": true, - "dates": []interface{}{1, 2, 3, 4, 4}, - "addedArr": []interface{}{1, 2, 3}, - "addedMap": map[string]interface{}{ - "first": map[string]interface{}{ - "embedded": true, - }, - }, -} - -var chg = []interface{}{ - map[string]interface{}{ - "op": "add", - "path": "/addedArr", - "value": []interface{}{1, 2, 3}, - }, - map[string]interface{}{ - "op": "add", - "path": "/addedMap", - "value": map[string]interface{}{ - "first": map[string]interface{}{ - "embedded": true, - }, - }, - }, - map[string]interface{}{ - "op": "replace", - "path": "/age", - "value": 29, - }, - map[string]interface{}{ - "op": "add", - "path": "/changed", - "value": "This is a string", - }, - map[string]interface{}{ - "op": "remove", - "path": "/changing", - }, - map[string]interface{}{ - "op": "replace", - "path": "/dates/2", - "value": 3, - }, - map[string]interface{}{ - "op": "add", - "path": "/dates/3", - "value": 4, - }, - map[string]interface{}{ - "op": "add", - "path": "/dates/4", - "value": 4, - }, - map[string]interface{}{ - "op": "replace", - "path": "/different", - "value": true, - }, - map[string]interface{}{ - "op": "replace", - "path": "/item", - "value": sql.NewThing("test", 2), - }, - map[string]interface{}{ - "op": "change", - "path": "/name/first", - "value": "@@ -1 +1,5 @@\n T\n+obie\n", - }, - map[string]interface{}{ - "op": "change", - "path": "/name/last", - "value": "@@ -1,3 +1,16 @@\n M\n- H\n+organ Hitchcock\n", - }, -} - -func TestMain(t *testing.T) { - - var obj interface{} - var dif []interface{} - - Convey("Confirm that the item can be diffed correctly", t, func() { - dif = Diff(old, now) - So(dif, ShouldResemble, chg) - }) - - Convey("Confirm that the item can be patched correctly", t, func() { - obj = Patch(old, dif) - So(obj, ShouldResemble, now) - }) - -} - -func BenchmarkDiff(b *testing.B) { - - for n := 0; n < b.N; n++ { - Diff(old, now) - } - -} - -func BenchmarkPatch(b *testing.B) { - - for n := 0; n < b.N; n++ { - Patch(old, chg) - } - -} diff --git a/util/dupe/dupe.go b/util/dupe/dupe.go deleted file mode 100644 index ad83c778..00000000 --- a/util/dupe/dupe.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package dupe - -type Copyable interface { - Copy() interface{} -} - -type Cloneable interface { - Clone() interface{} -} - -func Duplicate(v interface{}) interface{} { - - switch x := v.(type) { - case map[string]interface{}: - out := make(map[string]interface{}, len(x)) - for k, v := range x { - switch y := v.(type) { - case map[string]interface{}: - out[k] = Duplicate(y) - case []interface{}: - out[k] = Duplicate(y) - default: - out[k] = y - } - } - return out - case []interface{}: - out := make([]interface{}, len(x)) - for k, v := range x { - switch y := v.(type) { - case map[string]interface{}: - out[k] = Duplicate(y) - case []interface{}: - out[k] = Duplicate(y) - default: - out[k] = y - } - } - return out - case Cloneable: - return x.Clone() - case Copyable: - return x.Copy() - default: - return x - } - -} diff --git a/util/fake/bool.go b/util/fake/bool.go deleted file mode 100644 index 4c9f5a3b..00000000 --- a/util/fake/bool.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -func Bool() bool { - return New().Bool() -} - -func (f *Faker) Bool() bool { - return 0.5 <= f.r.Float64() -} diff --git a/util/fake/char.go b/util/fake/char.go deleted file mode 100644 index 982ecac9..00000000 --- a/util/fake/char.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -var vowels = "aeoui" - -var consonants = "bcdfghjklmnpqrstvwxyz" - -var lowerchars = "abcdefghijklmnopqrstuvwxyz" - -var upperchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - -var alphachars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - -var alphanumbs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" - -func Alphanum() string { - return New().Alphanum() -} - -func (f *Faker) Alphanum() string { - return string(alphanumbs[f.r.Intn(len(alphanumbs))]) -} - -func Char() string { - return New().Char() -} - -func (f *Faker) Char() string { - return string(alphachars[f.r.Intn(len(alphachars))]) -} - -func CharLower() string { - return New().CharLower() -} - -func (f *Faker) CharLower() string { - return string(lowerchars[f.r.Intn(len(lowerchars))]) -} - -func CharUpper() string { - return New().CharUpper() -} - -func (f *Faker) CharUpper() string { - return string(upperchars[f.r.Intn(len(upperchars))]) -} - -func CharVowel() string { - return New().CharVowel() -} - -func (f *Faker) CharVowel() string { - return string(vowels[f.r.Intn(len(vowels))]) -} - -func CharConsonant() string { - return New().CharConsonant() -} - -func (f *Faker) CharConsonant() string { - return string(consonants[f.r.Intn(len(consonants))]) -} diff --git a/util/fake/company.go b/util/fake/company.go deleted file mode 100644 index 9d5915d5..00000000 --- a/util/fake/company.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -var companies = []string{"3Com Corp", "3M Company", "A.G. Edwards Inc.", "Abbott Laboratories", "Abercrombie & Fitch Co.", "ABM Industries Incorporated", "Ace Hardware Corporation", "ACT Manufacturing Inc.", "Acterna Corp.", "Adams Resources & Energy, Inc.", "ADC Telecommunications, Inc.", "Adelphia Communications Corporation", "Administaff, Inc.", "Adobe Systems Incorporated", "Adolph Coors Company", "Advance Auto Parts, Inc.", "Advanced Micro Devices, Inc.", "AdvancePCS, Inc.", "Advantica Restaurant Group, Inc.", "The AES Corporation", "Aetna Inc.", "Affiliated Computer Services, Inc.", "AFLAC Incorporated", "AGCO Corporation", "Agilent Technologies, Inc.", "Agway Inc.", "Apartment Investment and Management Company", "Air Products and Chemicals, Inc.", "Airborne, Inc.", "Airgas, Inc.", "AK Steel Holding Corporation", "Alaska Air Group, Inc.", "Alberto-Culver Company", "Albertson's, Inc.", "Alcoa Inc.", "Alleghany Corporation", "Allegheny Energy, Inc.", "Allegheny Technologies Incorporated", "Allergan, Inc.", "ALLETE, Inc.", "Alliant Energy Corporation", "Allied Waste Industries, Inc.", "Allmerica Financial Corporation", "The Allstate Corporation", "ALLTEL Corporation", "The Alpine Group, Inc.", "Amazon.com, Inc.", "AMC Entertainment Inc.", "American Power Conversion Corporation", "Amerada Hess Corporation", "AMERCO", "Ameren Corporation", "America West Holdings Corporation", "American Axle & Manufacturing Holdings, Inc.", "American Eagle Outfitters, Inc.", "American Electric Power Company, Inc.", "American Express Company", "American Financial Group, Inc.", "American Greetings Corporation", "American International Group, Inc.", "American Standard Companies Inc.", "American Water Works Company, Inc.", "AmerisourceBergen Corporation", "Ames Department Stores, Inc.", "Amgen Inc.", "Amkor Technology, Inc.", "AMR Corporation", "AmSouth Bancorp.", "Amtran, Inc.", "Anadarko Petroleum Corporation", "Analog Devices, Inc.", "Anheuser-Busch Companies, Inc.", "Anixter International Inc.", "AnnTaylor Inc.", "Anthem, Inc.", "AOL Time Warner Inc.", "Aon Corporation", "Apache Corporation", "Apple Computer, Inc.", "Applera Corporation", "Applied Industrial Technologies, Inc.", "Applied Materials, Inc.", "Aquila, Inc.", "ARAMARK Corporation", "Arch Coal, Inc.", "Archer Daniels Midland Company", "Arkansas Best Corporation", "Armstrong Holdings, Inc.", "Arrow Electronics, Inc.", "ArvinMeritor, Inc.", "Ashland Inc.", "Astoria Financial Corporation", "AT&T Corp.", "Atmel Corporation", "Atmos Energy Corporation", "Audiovox Corporation", "Autoliv, Inc.", "Automatic Data Processing, Inc.", "AutoNation, Inc.", "AutoZone, Inc.", "Avaya Inc.", "Avery Dennison Corporation", "Avista Corporation", "Avnet, Inc.", "Avon Products, Inc.", "Baker Hughes Incorporated", "Ball Corporation", "Bank of America Corporation", "The Bank of New York Company, Inc.", "Bank One Corporation", "Banknorth Group, Inc.", "Banta Corporation", "Barnes & Noble, Inc.", "Bausch & Lomb Incorporated", "Baxter International Inc.", "BB&T Corporation", "The Bear Stearns Companies Inc.", "Beazer Homes USA, Inc.", "Beckman Coulter, Inc.", "Becton, Dickinson and Company", "Bed Bath & Beyond Inc.", "Belk, Inc.", "Bell Microproducts Inc.", "BellSouth Corporation", "Belo Corp.", "Bemis Company, Inc.", "Benchmark Electronics, Inc.", "Berkshire Hathaway Inc.", "Best Buy Co., Inc.", "Bethlehem Steel Corporation", "Beverly Enterprises, Inc.", "Big Lots, Inc.", "BJ Services Company", "BJ's Wholesale Club, Inc.", "The Black & Decker Corporation", "Black Hills Corporation", "BMC Software, Inc.", "The Boeing Company", "Boise Cascade Corporation", "Borders Group, Inc.", "BorgWarner Inc.", "Boston Scientific Corporation", "Bowater Incorporated", "Briggs & Stratton Corporation", "Brightpoint, Inc.", "Brinker International, Inc.", "Bristol-Myers Squibb Company", "Broadwing, Inc.", "Brown Shoe Company, Inc.", "Brown-Forman Corporation", "Brunswick Corporation", "Budget Group, Inc.", "Burlington Coat Factory Warehouse Corporation", "Burlington Industries, Inc.", "Burlington Northern Santa Fe Corporation", "Burlington Resources Inc.", "C. H. Robinson Worldwide Inc.", "Cablevision Systems Corp", "Cabot Corp", "Cadence Design Systems, Inc.", "Calpine Corp.", "Campbell Soup Co.", "Capital One Financial Corp.", "Cardinal Health Inc.", "Caremark Rx Inc.", "Carlisle Cos. Inc.", "Carpenter Technology Corp.", "Casey's General Stores Inc.", "Caterpillar Inc.", "CBRL Group Inc.", "CDI Corp.", "CDW Computer Centers Inc.", "CellStar Corp.", "Cendant Corp", "Cenex Harvest States Cooperatives", "Centex Corp.", "CenturyTel Inc.", "Ceridian Corp.", "CH2M Hill Cos. Ltd.", "Champion Enterprises Inc.", "Charles Schwab Corp.", "Charming Shoppes Inc.", "Charter Communications Inc.", "Charter One Financial Inc.", "ChevronTexaco Corp.", "Chiquita Brands International Inc.", "Chubb Corp", "Ciena Corp.", "Cigna Corp", "Cincinnati Financial Corp.", "Cinergy Corp.", "Cintas Corp.", "Circuit City Stores Inc.", "Cisco Systems Inc.", "Citigroup, Inc", "Citizens Communications Co.", "CKE Restaurants Inc.", "Clear Channel Communications Inc.", "The Clorox Co.", "CMGI Inc.", "CMS Energy Corp.", "CNF Inc.", "Coca-Cola Co.", "Coca-Cola Enterprises Inc.", "Colgate-Palmolive Co.", "Collins & Aikman Corp.", "Comcast Corp.", "Comdisco Inc.", "Comerica Inc.", "Comfort Systems USA Inc.", "Commercial Metals Co.", "Community Health Systems Inc.", "Compass Bancshares Inc", "Computer Associates International Inc.", "Computer Sciences Corp.", "Compuware Corp.", "Comverse Technology Inc.", "ConAgra Foods Inc.", "Concord EFS Inc.", "Conectiv, Inc", "Conoco Inc", "Conseco Inc.", "Consolidated Freightways Corp.", "Consolidated Edison Inc.", "Constellation Brands Inc.", "Constellation Emergy Group Inc.", "Continental Airlines Inc.", "Convergys Corp.", "Cooper Cameron Corp.", "Cooper Industries Ltd.", "Cooper Tire & Rubber Co.", "Corn Products International Inc.", "Corning Inc.", "Costco Wholesale Corp.", "Countrywide Credit Industries Inc.", "Coventry Health Care Inc.", "Cox Communications Inc.", "Crane Co.", "Crompton Corp.", "Crown Cork & Seal Co. Inc.", "CSK Auto Corp.", "CSX Corp.", "Cummins Inc.", "CVS Corp.", "Cytec Industries Inc.", "D&K Healthcare Resources, Inc.", "D.R. Horton Inc.", "Dana Corporation", "Danaher Corporation", "Darden Restaurants Inc.", "DaVita Inc.", "Dean Foods Company", "Deere & Company", "Del Monte Foods Co", "Dell Computer Corporation", "Delphi Corp.", "Delta Air Lines Inc.", "Deluxe Corporation", "Devon Energy Corporation", "Di Giorgio Corporation", "Dial Corporation", "Diebold Incorporated", "Dillard's Inc.", "DIMON Incorporated", "Dole Food Company, Inc.", "Dollar General Corporation", "Dollar Tree Stores, Inc.", "Dominion Resources, Inc.", "Domino's Pizza LLC", "Dover Corporation, Inc.", "Dow Chemical Company", "Dow Jones & Company, Inc.", "DPL Inc.", "DQE Inc.", "Dreyer's Grand Ice Cream, Inc.", "DST Systems, Inc.", "DTE Energy Co.", "E.I. Du Pont de Nemours and Company", "Duke Energy Corp", "Dun & Bradstreet Inc.", "DURA Automotive Systems Inc.", "DynCorp", "Dynegy Inc.", "E*Trade Group, Inc.", "E.W. Scripps Company", "Earthlink, Inc.", "Eastman Chemical Company", "Eastman Kodak Company", "Eaton Corporation", "Echostar Communications Corporation", "Ecolab Inc.", "Edison International", "EGL Inc.", "El Paso Corporation", "Electronic Arts Inc.", "Electronic Data Systems Corp.", "Eli Lilly and Company", "EMC Corporation", "Emcor Group Inc.", "Emerson Electric Co.", "Encompass Services Corporation", "Energizer Holdings Inc.", "Energy East Corporation", "Engelhard Corporation", "Enron Corp.", "Entergy Corporation", "Enterprise Products Partners L.P.", "EOG Resources, Inc.", "Equifax Inc.", "Equitable Resources Inc.", "Equity Office Properties Trust", "Equity Residential Properties Trust", "Estee Lauder Companies Inc.", "Exelon Corporation", "Exide Technologies", "Expeditors International of Washington Inc.", "Express Scripts Inc.", "ExxonMobil Corporation", "Fairchild Semiconductor International Inc.", "Family Dollar Stores Inc.", "Farmland Industries Inc.", "Federal Mogul Corp.", "Federated Department Stores Inc.", "Federal Express Corp.", "Felcor Lodging Trust Inc.", "Ferro Corp.", "Fidelity National Financial Inc.", "Fifth Third Bancorp", "First American Financial Corp.", "First Data Corp.", "First National of Nebraska Inc.", "First Tennessee National Corp.", "FirstEnergy Corp.", "Fiserv Inc.", "Fisher Scientific International Inc.", "FleetBoston Financial Co.", "Fleetwood Enterprises Inc.", "Fleming Companies Inc.", "Flowers Foods Inc.", "Flowserv Corp", "Fluor Corp", "FMC Corp", "Foamex International Inc", "Foot Locker Inc", "Footstar Inc.", "Ford Motor Co", "Forest Laboratories Inc.", "Fortune Brands Inc.", "Foster Wheeler Ltd.", "FPL Group Inc.", "Franklin Resources Inc.", "Freeport McMoran Copper & Gold Inc.", "Frontier Oil Corp", "Furniture Brands International Inc.", "Gannett Co., Inc.", "Gap Inc.", "Gateway Inc.", "GATX Corporation", "Gemstar-TV Guide International Inc.", "GenCorp Inc.", "General Cable Corporation", "General Dynamics Corporation", "General Electric Company", "General Mills Inc", "General Motors Corporation", "Genesis Health Ventures Inc.", "Gentek Inc.", "Gentiva Health Services Inc.", "Genuine Parts Company", "Genuity Inc.", "Genzyme Corporation", "Georgia Gulf Corporation", "Georgia-Pacific Corporation", "Gillette Company", "Gold Kist Inc.", "Golden State Bancorp Inc.", "Golden West Financial Corporation", "Goldman Sachs Group Inc.", "Goodrich Corporation", "The Goodyear Tire & Rubber Company", "Granite Construction Incorporated", "Graybar Electric Company Inc.", "Great Lakes Chemical Corporation", "Great Plains Energy Inc.", "GreenPoint Financial Corp.", "Greif Bros. Corporation", "Grey Global Group Inc.", "Group 1 Automotive Inc.", "Guidant Corporation", "H&R Block Inc.", "H.B. Fuller Company", "H.J. Heinz Company", "Halliburton Co.", "Harley-Davidson Inc.", "Harman International Industries Inc.", "Harrah's Entertainment Inc.", "Harris Corp.", "Harsco Corp.", "Hartford Financial Services Group Inc.", "Hasbro Inc.", "Hawaiian Electric Industries Inc.", "HCA Inc.", "Health Management Associates Inc.", "Health Net Inc.", "Healthsouth Corp", "Henry Schein Inc.", "Hercules Inc.", "Herman Miller Inc.", "Hershey Foods Corp.", "Hewlett-Packard Company", "Hibernia Corp.", "Hillenbrand Industries Inc.", "Hilton Hotels Corp.", "Hollywood Entertainment Corp.", "Home Depot Inc.", "Hon Industries Inc.", "Honeywell International Inc.", "Hormel Foods Corp.", "Host Marriott Corp.", "Household International Corp.", "Hovnanian Enterprises Inc.", "Hub Group Inc.", "Hubbell Inc.", "Hughes Supply Inc.", "Humana Inc.", "Huntington Bancshares Inc.", "Idacorp Inc.", "IDT Corporation", "IKON Office Solutions Inc.", "Illinois Tool Works Inc.", "IMC Global Inc.", "Imperial Sugar Company", "IMS Health Inc.", "Ingles Market Inc", "Ingram Micro Inc.", "Insight Enterprises Inc.", "Integrated Electrical Services Inc.", "Intel Corporation", "International Paper Co.", "Interpublic Group of Companies Inc.", "Interstate Bakeries Corporation", "International Business Machines Corp.", "International Flavors & Fragrances Inc.", "International Multifoods Corporation", "Intuit Inc.", "IT Group Inc.", "ITT Industries Inc.", "Ivax Corp.", "J.B. Hunt Transport Services Inc.", "J.C. Penny Co.", "J.P. Morgan Chase & Co.", "Jabil Circuit Inc.", "Jack In The Box Inc.", "Jacobs Engineering Group Inc.", "JDS Uniphase Corp.", "Jefferson-Pilot Co.", "John Hancock Financial Services Inc.", "Johnson & Johnson", "Johnson Controls Inc.", "Jones Apparel Group Inc.", "KB Home", "Kellogg Company", "Kellwood Company", "Kelly Services Inc.", "Kemet Corp.", "Kennametal Inc.", "Kerr-McGee Corporation", "KeyCorp", "KeySpan Corp.", "Kimball International Inc.", "Kimberly-Clark Corporation", "Kindred Healthcare Inc.", "KLA-Tencor Corporation", "K-Mart Corp.", "Knight-Ridder Inc.", "Kohl's Corp.", "KPMG Consulting Inc.", "Kroger Co.", "L-3 Communications Holdings Inc.", "Laboratory Corporation of America Holdings", "Lam Research Corporation", "LandAmerica Financial Group Inc.", "Lands' End Inc.", "Landstar System Inc.", "La-Z-Boy Inc.", "Lear Corporation", "Legg Mason Inc.", "Leggett & Platt Inc.", "Lehman Brothers Holdings Inc.", "Lennar Corporation", "Lennox International Inc.", "Level 3 Communications Inc.", "Levi Strauss & Co.", "Lexmark International Inc.", "Limited Inc.", "Lincoln National Corporation", "Linens 'n Things Inc.", "Lithia Motors Inc.", "Liz Claiborne Inc.", "Lockheed Martin Corporation", "Loews Corporation", "Longs Drug Stores Corporation", "Louisiana-Pacific Corporation", "Lowe's Companies Inc.", "LSI Logic Corporation", "The LTV Corporation", "The Lubrizol Corporation", "Lucent Technologies Inc.", "Lyondell Chemical Company", "M & T Bank Corporation", "Magellan Health Services Inc.", "Mail-Well Inc.", "Mandalay Resort Group", "Manor Care Inc.", "Manpower Inc.", "Marathon Oil Corporation", "Mariner Health Care Inc.", "Markel Corporation", "Marriott International Inc.", "Marsh & McLennan Companies Inc.", "Marsh Supermarkets Inc.", "Marshall & Ilsley Corporation", "Martin Marietta Materials Inc.", "Masco Corporation", "Massey Energy Company", "MasTec Inc.", "Mattel Inc.", "Maxim Integrated Products Inc.", "Maxtor Corporation", "Maxxam Inc.", "The May Department Stores Company", "Maytag Corporation", "MBNA Corporation", "McCormick & Company Incorporated", "McDonald's Corporation", "The McGraw-Hill Companies Inc.", "McKesson Corporation", "McLeodUSA Incorporated", "M.D.C. Holdings Inc.", "MDU Resources Group Inc.", "MeadWestvaco Corporation", "Medtronic Inc.", "Mellon Financial Corporation", "The Men's Wearhouse Inc.", "Merck & Co., Inc.", "Mercury General Corporation", "Merrill Lynch & Co. Inc.", "Metaldyne Corporation", "Metals USA Inc.", "MetLife Inc.", "Metris Companies Inc", "MGIC Investment Corporation", "MGM Mirage", "Michaels Stores Inc.", "Micron Technology Inc.", "Microsoft Corporation", "Milacron Inc.", "Millennium Chemicals Inc.", "Mirant Corporation", "Mohawk Industries Inc.", "Molex Incorporated", "The MONY Group Inc.", "Morgan Stanley Dean Witter & Co.", "Motorola Inc.", "MPS Group Inc.", "Murphy Oil Corporation", "Nabors Industries Inc", "Nacco Industries Inc", "Nash Finch Company", "National City Corp.", "National Commerce Financial Corporation", "National Fuel Gas Company", "National Oilwell Inc", "National Rural Utilities Cooperative Finance Corporation", "National Semiconductor Corporation", "National Service Industries Inc", "Navistar International Corporation", "NCR Corporation", "The Neiman Marcus Group Inc.", "New Jersey Resources Corporation", "New York Times Company", "Newell Rubbermaid Inc", "Newmont Mining Corporation", "Nextel Communications Inc", "Nicor Inc", "Nike Inc", "NiSource Inc", "Noble Energy Inc", "Nordstrom Inc", "Norfolk Southern Corporation", "Nortek Inc", "North Fork Bancorporation Inc", "Northeast Utilities System", "Northern Trust Corporation", "Northrop Grumman Corporation", "NorthWestern Corporation", "Novellus Systems Inc", "NSTAR", "NTL Incorporated", "Nucor Corp", "Nvidia Corp", "NVR Inc", "Northwest Airlines Corp", "Occidental Petroleum Corp", "Ocean Energy Inc", "Office Depot Inc.", "OfficeMax Inc", "OGE Energy Corp", "Oglethorpe Power Corp.", "Ohio Casualty Corp.", "Old Republic International Corp.", "Olin Corp.", "OM Group Inc", "Omnicare Inc", "Omnicom Group", "On Semiconductor Corp", "ONEOK Inc", "Oracle Corp", "Oshkosh Truck Corp", "Outback Steakhouse Inc.", "Owens & Minor Inc.", "Owens Corning", "Owens-Illinois Inc", "Oxford Health Plans Inc", "Paccar Inc", "PacifiCare Health Systems Inc", "Packaging Corp. of America", "Pactiv Corp", "Pall Corp", "Pantry Inc", "Park Place Entertainment Corp", "Parker Hannifin Corp.", "Pathmark Stores Inc.", "Paychex Inc", "Payless Shoesource Inc", "Penn Traffic Co.", "Pennzoil-Quaker State Company", "Pentair Inc", "Peoples Energy Corp.", "PeopleSoft Inc", "Pep Boys Manny, Moe & Jack", "Potomac Electric Power Co.", "Pepsi Bottling Group Inc.", "PepsiAmericas Inc.", "PepsiCo Inc.", "Performance Food Group Co.", "Perini Corp", "PerkinElmer Inc", "Perot Systems Corp", "Petco Animal Supplies Inc.", "Peter Kiewit Sons', Inc.", "PETsMART Inc", "Pfizer Inc", "Pacific Gas & Electric Corp.", "Pharmacia Corp", "Phar Mor Inc.", "Phelps Dodge Corp.", "Philip Morris Companies Inc.", "Phillips Petroleum Co", "Phillips Van Heusen Corp.", "Phoenix Companies Inc", "Pier 1 Imports Inc.", "Pilgrim's Pride Corporation", "Pinnacle West Capital Corp", "Pioneer-Standard Electronics Inc.", "Pitney Bowes Inc.", "Pittston Brinks Group", "Plains All American Pipeline LP", "PNC Financial Services Group Inc.", "PNM Resources Inc", "Polaris Industries Inc.", "Polo Ralph Lauren Corp", "PolyOne Corp", "Popular Inc", "Potlatch Corp", "PPG Industries Inc", "PPL Corp", "Praxair Inc", "Precision Castparts Corp", "Premcor Inc.", "Pride International Inc", "Primedia Inc", "Principal Financial Group Inc.", "Procter & Gamble Co.", "Pro-Fac Cooperative Inc.", "Progress Energy Inc", "Progressive Corporation", "Protective Life Corp", "Provident Financial Group", "Providian Financial Corp.", "Prudential Financial Inc.", "PSS World Medical Inc", "Public Service Enterprise Group Inc.", "Publix Super Markets Inc.", "Puget Energy Inc.", "Pulte Homes Inc", "Qualcomm Inc", "Quanta Services Inc.", "Quantum Corp", "Quest Diagnostics Inc.", "Questar Corp", "Quintiles Transnational", "Qwest Communications Intl Inc", "R.J. Reynolds Tobacco Company", "R.R. Donnelley & Sons Company", "Radio Shack Corporation", "Raymond James Financial Inc.", "Raytheon Company", "Reader's Digest Association Inc.", "Reebok International Ltd.", "Regions Financial Corp.", "Regis Corporation", "Reliance Steel & Aluminum Co.", "Reliant Energy Inc.", "Rent A Center Inc", "Republic Services Inc", "Revlon Inc", "RGS Energy Group Inc", "Rite Aid Corp", "Riverwood Holding Inc.", "RoadwayCorp", "Robert Half International Inc.", "Rock-Tenn Co", "Rockwell Automation Inc", "Rockwell Collins Inc", "Rohm & Haas Co.", "Ross Stores Inc", "RPM Inc.", "Ruddick Corp", "Ryder System Inc", "Ryerson Tull Inc", "Ryland Group Inc.", "Sabre Holdings Corp", "Safeco Corp", "Safeguard Scientifics Inc.", "Safeway Inc", "Saks Inc", "Sanmina-SCI Inc", "Sara Lee Corp", "SBC Communications Inc", "Scana Corp.", "Schering-Plough Corp", "Scholastic Corp", "SCI Systems Onc.", "Science Applications Intl. Inc.", "Scientific-Atlanta Inc", "Scotts Company", "Seaboard Corp", "Sealed Air Corp", "Sears Roebuck & Co", "Sempra Energy", "Sequa Corp", "Service Corp. International", "ServiceMaster Co", "Shaw Group Inc", "Sherwin-Williams Company", "Shopko Stores Inc", "Siebel Systems Inc", "Sierra Health Services Inc", "Sierra Pacific Resources", "Silgan Holdings Inc.", "Silicon Graphics Inc", "Simon Property Group Inc", "SLM Corporation", "Smith International Inc", "Smithfield Foods Inc", "Smurfit-Stone Container Corp", "Snap-On Inc", "Solectron Corp", "Solutia Inc", "Sonic Automotive Inc.", "Sonoco Products Co.", "Southern Company", "Southern Union Company", "SouthTrust Corp.", "Southwest Airlines Co", "Southwest Gas Corp", "Sovereign Bancorp Inc.", "Spartan Stores Inc", "Spherion Corp", "Sports Authority Inc", "Sprint Corp.", "SPX Corp", "St. Jude Medical Inc", "St. Paul Cos.", "Staff Leasing Inc.", "StanCorp Financial Group Inc", "Standard Pacific Corp.", "Stanley Works", "Staples Inc", "Starbucks Corp", "Starwood Hotels & Resorts Worldwide Inc", "State Street Corp.", "Stater Bros. Holdings Inc.", "Steelcase Inc", "Stein Mart Inc", "Stewart & Stevenson Services Inc", "Stewart Information Services Corp", "Stilwell Financial Inc", "Storage Technology Corporation", "Stryker Corp", "Sun Healthcare Group Inc.", "Sun Microsystems Inc.", "SunGard Data Systems Inc.", "Sunoco Inc.", "SunTrust Banks Inc", "Supervalu Inc", "Swift Transportation, Co., Inc", "Symbol Technologies Inc", "Synovus Financial Corp.", "Sysco Corp", "Systemax Inc.", "Target Corp.", "Tech Data Corporation", "TECO Energy Inc", "Tecumseh Products Company", "Tektronix Inc", "Teleflex Incorporated", "Telephone & Data Systems Inc", "Tellabs Inc.", "Temple-Inland Inc", "Tenet Healthcare Corporation", "Tenneco Automotive Inc.", "Teradyne Inc", "Terex Corp", "Tesoro Petroleum Corp.", "Texas Industries Inc.", "Texas Instruments Incorporated", "Textron Inc", "Thermo Electron Corporation", "Thomas & Betts Corporation", "Tiffany & Co", "Timken Company", "TJX Companies Inc", "TMP Worldwide Inc", "Toll Brothers Inc", "Torchmark Corporation", "Toro Company", "Tower Automotive Inc.", "Toys 'R' Us Inc", "Trans World Entertainment Corp.", "TransMontaigne Inc", "Transocean Inc", "TravelCenters of America Inc.", "Triad Hospitals Inc", "Tribune Company", "Trigon Healthcare Inc.", "Trinity Industries Inc", "Trump Hotels & Casino Resorts Inc.", "TruServ Corporation", "TRW Inc", "TXU Corp", "Tyson Foods Inc", "U.S. Bancorp", "U.S. Industries Inc.", "UAL Corporation", "UGI Corporation", "Unified Western Grocers Inc", "Union Pacific Corporation", "Union Planters Corp", "Unisource Energy Corp", "Unisys Corporation", "United Auto Group Inc", "United Defense Industries Inc.", "United Parcel Service Inc", "United Rentals Inc", "United Stationers Inc", "United Technologies Corporation", "UnitedHealth Group Incorporated", "Unitrin Inc", "Universal Corporation", "Universal Forest Products Inc", "Universal Health Services Inc", "Unocal Corporation", "Unova Inc", "UnumProvident Corporation", "URS Corporation", "US Airways Group Inc", "US Oncology Inc", "USA Interactive", "USFreighways Corporation", "USG Corporation", "UST Inc", "Valero Energy Corporation", "Valspar Corporation", "Value City Department Stores Inc", "Varco International Inc", "Vectren Corporation", "Veritas Software Corporation", "Verizon Communications Inc", "VF Corporation", "Viacom Inc", "Viad Corp", "Viasystems Group Inc", "Vishay Intertechnology Inc", "Visteon Corporation", "Volt Information Sciences Inc", "Vulcan Materials Company", "W.R. Berkley Corporation", "W.R. Grace & Co", "W.W. Grainger Inc", "Wachovia Corporation", "Wakenhut Corporation", "Walgreen Co", "Wallace Computer Services Inc", "Wal-Mart Stores Inc", "Walt Disney Co", "Walter Industries Inc", "Washington Mutual Inc", "Washington Post Co.", "Waste Management Inc", "Watsco Inc", "Weatherford International Inc", "Weis Markets Inc.", "Wellpoint Health Networks Inc", "Wells Fargo & Company", "Wendy's International Inc", "Werner Enterprises Inc", "WESCO International Inc", "Western Digital Inc", "Western Gas Resources Inc", "WestPoint Stevens Inc", "Weyerhauser Company", "WGL Holdings Inc", "Whirlpool Corporation", "Whole Foods Market Inc", "Willamette Industries Inc.", "Williams Companies Inc", "Williams Sonoma Inc", "Winn Dixie Stores Inc", "Wisconsin Energy Corporation", "Wm Wrigley Jr Company", "World Fuel Services Corporation", "WorldCom Inc", "Worthington Industries Inc", "WPS Resources Corporation", "Wyeth", "Wyndham International Inc", "Xcel Energy Inc", "Xerox Corp", "Xilinx Inc", "XO Communications Inc", "Yellow Corporation", "York International Corp", "Yum Brands Inc.", "Zale Corporation", "Zions Bancorporation"} - -var industries = []string{"Aeronautics and Defence", "Alternative Investment Instruments", "Automotive and Parts", "Banking", "Beverages", "Building and Materials", "Commercial Transportation", "Domestic Goods", "Electricity Generation and Distribution", "Electronic & Electrical Equipment", "Engineering Products", "Financials", "Food Products", "Forestry & Paper", "Fossil Fuels and Distribution", "Health Care and Related Services", "Household Utilities", "Industrial Chemicals", "Industrials", "Insurance", "Investment Companies", "IT Hardware", "IT Services", "Leisure Products", "Media", "Medicine and Biotech Research", "Metals", "Mining", "Personal Goods", "Property", "Retailers", "Support", "Telecommunications", "Tobacco", "Tourism and Leisure"} - -func CompanyName() string { - return New().CompanyName() -} - -func (f *Faker) CompanyName() string { - return companies[f.r.Intn(len(companies))] -} - -func CompanyIndustry() string { - return New().CompanyIndustry() -} - -func (f *Faker) CompanyIndustry() string { - return industries[f.r.Intn(len(industries))] -} diff --git a/util/fake/fake.go b/util/fake/fake.go deleted file mode 100644 index 08b39603..00000000 --- a/util/fake/fake.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "math/rand" - "time" -) - -func init() { - rand.Seed(time.Now().UTC().UnixNano()) -} - -type Faker struct { - r *rand.Rand -} - -func New() *Faker { - s := time.Now().UTC().UnixNano() - return &Faker{r: rand.New(rand.NewSource(s))} -} diff --git a/util/fake/guid.go b/util/fake/guid.go deleted file mode 100644 index 862e9b4d..00000000 --- a/util/fake/guid.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "github.com/surrealdb/surrealdb/util/guid" -) - -func Guid() string { - return guid.New().String() -} - -func (f *Faker) Guid() string { - return guid.New().String() -} diff --git a/util/fake/latin.go b/util/fake/latin.go deleted file mode 100644 index 90722f4d..00000000 --- a/util/fake/latin.go +++ /dev/null @@ -1,3560 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -var latin = [...]string{ - "a", - "ab", - "abditioribus", - "abditis", - "abesset", - "abiciam", - "abiciendum", - "abigo", - "aboleatur", - "abs", - "absconderem", - "absconditi", - "abscondo", - "absentia", - "absit", - "absorbui", - "absorbuit", - "absorpta", - "abstinentia", - "abstrusioribus", - "absunt", - "absurdissimum", - "abundabimus", - "abundantiore", - "abundare", - "abyssos", - "abyssus", - "ac", - "accedam", - "accedimus", - "accedit", - "accende", - "accepimus", - "accepisse", - "acceptabilia", - "acceptam", - "accidit", - "accipiat", - "actione", - "actiones", - "actionibus", - "ad", - "adamavi", - "addiderunt", - "adducor", - "adduxerunt", - "aderat", - "adesset", - "adest", - "adflatu", - "adhaesit", - "adhibemus", - "adhuc", - "adipiscendae", - "adipisci", - "aditu", - "aditum", - "adiungit", - "adlapsu", - "admiratio", - "admittantur", - "admitti", - "admoneas", - "admonente", - "admoniti", - "adparere", - "adparet", - "adpellata", - "adpetere", - "adprehendit", - "adprobamus", - "adprobandi", - "adpropinquet", - "adquiescat", - "adquiesco", - "adsensum", - "adsit", - "adsuefacta", - "adsunt", - "adsurgat", - "adsurgere", - "adtendi", - "adveriarius", - "adversa", - "adversis", - "adversitas", - "adversitatibus", - "adversitatis", - "adversus", - "advertenti", - "advertimus", - "aedificasti", - "aeger", - "aegre", - "aegrotantes", - "aenigmate", - "aequalis", - "aequo", - "aer", - "aeris", - "aerumnosis", - "aerumnosum", - "aestimanda", - "aestimantur", - "aestimare", - "aestimem", - "aestus", - "aetate", - "affectent", - "affectio", - "affectiones", - "affectionum", - "affectu", - "affectum", - "affectus", - "afficior", - "afficit", - "afuerit", - "agam", - "agantur", - "agatur", - "agebam", - "agenti", - "agerem", - "agit", - "agitaveram", - "agitis", - "agito", - "agnoscendo", - "agnoscere", - "agnoscerem", - "agnosceremus", - "agnoscerent", - "agnoscimus", - "agnosco", - "agnovi", - "ago", - "agro", - "ait", - "alas", - "album", - "alexandrino", - "alia", - "aliae", - "aliam", - "alias", - "alibi", - "alicui", - "alienam", - "alieni", - "alieno", - "alienorum", - "alii", - "aliis", - "alimenta", - "alimentorum", - "alio", - "alioquin", - "alios", - "aliqua", - "aliquam", - "aliquando", - "aliquantulum", - "aliquantum", - "aliquid", - "aliquo", - "aliquod", - "alis", - "aliter", - "aliterque", - "aliud", - "alium", - "alius", - "alta", - "alter", - "altera", - "alteram", - "alteri", - "alterum", - "altius", - "amamus", - "amandum", - "amant", - "amare", - "amaremus", - "amarent", - "amari", - "amaris", - "amaritudo", - "amarus", - "amasti", - "amat", - "amatoribus", - "amatur", - "amavi", - "ambiendum", - "ambitione", - "ambitiones", - "ambitum", - "ambulasti", - "ambulent", - "amem", - "amemur", - "amet", - "ametur", - "amicum", - "amisi", - "amissum", - "amittere", - "amo", - "amoenos", - "amor", - "amore", - "amorem", - "amplexibus", - "amplexum", - "amplior", - "amplitudines", - "amplius", - "amplum", - "an", - "anaximenes", - "angelos", - "angelum", - "angustus", - "anhelo", - "anima", - "animadvertendo", - "animadverterunt", - "animae", - "animales", - "animalia", - "animalibus", - "animam", - "animant", - "animarum", - "animas", - "animi", - "animo", - "animos", - "animum", - "animus", - "ante", - "antepono", - "antequam", - "antiqua", - "antiquis", - "antris", - "aperit", - "appareat", - "apparens", - "apparet", - "apparuit", - "appetam", - "appetitu", - "appetitum", - "approbare", - "approbat", - "approbavi", - "approbet", - "apud", - "aqua", - "aquae", - "aquilone", - "aranea", - "araneae", - "arbitratus", - "ardentius", - "ardes", - "arguitur", - "aromatum", - "arrogantis", - "artes", - "artibus", - "artificiosas", - "artificosa", - "ascendam", - "ascendant", - "ascendens", - "aspectui", - "aspernatione", - "aspero", - "asperum", - "assecutus", - "assequitur", - "assuescere", - "assuescunt", - "assumunt", - "assumuntur", - "assunt", - "at", - "athanasio", - "atque", - "attamen", - "attigerit", - "attigi", - "attingam", - "attingere", - "attingi", - "audeo", - "audi", - "audiam", - "audiant", - "audiar", - "audiat", - "audiebam", - "audierint", - "audieris", - "audierit", - "audierunt", - "audio", - "audire", - "audis", - "audit", - "audito", - "auditur", - "audiunt", - "audiuntur", - "audivi", - "audivimus", - "aufer", - "augebis", - "augendo", - "augeret", - "auget", - "aula", - "auram", - "auras", - "aurem", - "aures", - "auri", - "auribus", - "auris", - "aurium", - "aut", - "autem", - "avaritiam", - "avertat", - "avertit", - "avertitur", - "aves", - "avide", - "beares", - "beata", - "beatae", - "beatam", - "beati", - "beatitudinis", - "beatos", - "beatum", - "beatus", - "bellum", - "bene", - "benedicendo", - "benedicere", - "benedicis", - "benedicitur", - "bestiae", - "bibendi", - "bibendo", - "bibo", - "blanditur", - "bona", - "bonae", - "bonam", - "bone", - "boni", - "bonis", - "bono", - "bonorumque", - "bonos", - "bonum", - "cadavere", - "cadere", - "cadunt", - "caecis", - "caecitatem", - "caecus", - "caelestium", - "caeli", - "caelo", - "caelum", - "calamitas", - "calciamentis", - "calidum", - "calumnientur", - "campis", - "campos", - "candorem", - "canem", - "canenti", - "canitur", - "canora", - "canoris", - "cantandi", - "cantantem", - "cantantur", - "cantarentur", - "cantilenarum", - "canto", - "cantu", - "cantus", - "capacitas", - "caperetur", - "capiamur", - "capiar", - "capiendum", - "capio", - "capior", - "capit", - "capiuntur", - "captans", - "captus", - "caput", - "careamus", - "carent", - "carentes", - "careo", - "carere", - "caritas", - "caritatis", - "carne", - "carneis", - "carnem", - "carneo", - "carnes", - "carnis", - "caro", - "carthaginem", - "carthaginis", - "castam", - "caste", - "castissime", - "casto", - "castrorum", - "casu", - "catervas", - "catervatim", - "causa", - "caveam", - "cavens", - "cavernis", - "cavis", - "cedendo", - "cedentibus", - "cedunt", - "celeritate", - "cellis", - "cepit", - "cernimus", - "certa", - "certe", - "certissimum", - "certissimus", - "certo", - "certum", - "certus", - "cervicem", - "cessant", - "cessare", - "cessas", - "cessatione", - "cessavit", - "cetera", - "ceterarumque", - "ceteri", - "ceteris", - "ceterorum", - "ceteros", - "christus", - "cibo", - "cibum", - "cibus", - "cinerem", - "circo", - "circumquaque", - "circumstant", - "circumstrepant", - "cito", - "civium", - "clamasti", - "clamat", - "clamore", - "claudicans", - "clauditur", - "coapta", - "coegerit", - "coepisti", - "coepta", - "cogenda", - "cogens", - "cogeremur", - "cogit", - "cogitamus", - "cogitando", - "cogitare", - "cogitarem", - "cogitari", - "cogitatione", - "cogitationibus", - "cogitationis", - "cogitetur", - "cogito", - "cogitur", - "cognitionis", - "cognitor", - "cognituri", - "cognitus", - "cognoscam", - "cognoscendam", - "cognoscendi", - "cognoscendum", - "cognoscere", - "cognosceremus", - "cognoscet", - "cognovi", - "cognovit", - "cogo", - "cohibeamus", - "cohiberi", - "colligantur", - "colligenda", - "colligere", - "colligimur", - "colligimus", - "colligitur", - "colligo", - "coloratae", - "colores", - "colorum", - "colunt", - "comes", - "comitatum", - "comitatur", - "comitum", - "commemini", - "commemoro", - "commendantur", - "commendata", - "commendatum", - "commendavi", - "commendavit", - "commune", - "commutantur", - "compagem", - "comprehendet", - "conantes", - "conatur", - "conatus", - "conceptaculum", - "concessisti", - "concludamus", - "concordiam", - "concubitu", - "concupiscentia", - "concupiscentiae", - "concupiscentiam", - "concupiscentias", - "concupiscit", - "concurrunt", - "condit", - "conduntur", - "conectitur", - "conexos", - "confecta", - "conferamus", - "conferunt", - "confessa", - "confessio", - "confessione", - "confessiones", - "confessionum", - "confitear", - "confitente", - "confitentem", - "confiteor", - "confiteri", - "confitetur", - "conforta", - "confortasti", - "confortat", - "congesta", - "congoscam", - "congratulari", - "congruentem", - "coniugio", - "coniunctam", - "coniunctione", - "conmemoravi", - "conmendat", - "conmixta", - "conmoniti", - "conmunem", - "conor", - "conperero", - "conprehendant", - "conprehenditur", - "conpressisti", - "conscientia", - "conscientiae", - "conscius", - "conscribebat", - "consensio", - "consensionem", - "consentiat", - "consequentibus", - "consequentium", - "considerabo", - "considerationem", - "consideravi", - "considero", - "consilium", - "consolatione", - "consonant", - "consonarent", - "consortium", - "conspectu", - "conspectum", - "conspiciant", - "conspiciatur", - "conspirantes", - "constans", - "constrictione", - "consuetudine", - "consuetudinem", - "consuetudinis", - "consuetudo", - "consuevit", - "consulebam", - "consulens", - "consulentibus", - "consulerem", - "consulunt", - "consumma", - "contemnat", - "contemnenda", - "contemnere", - "contemnit", - "contemptibilibus", - "contemptu", - "contendunt", - "contenti", - "conterritus", - "contexo", - "contineam", - "continebat", - "continens", - "continentiam", - "continet", - "contra", - "contractando", - "contrahit", - "contraria", - "contrario", - "contrectatae", - "contrectavi", - "contremunt", - "contristamur", - "contristari", - "contristat", - "contristatur", - "contristentur", - "contristor", - "contumelia", - "convenientissima", - "convertit", - "convinci", - "copia", - "copiarum", - "copiosae", - "copiosum", - "cor", - "coram", - "corda", - "corde", - "cordi", - "cordibus", - "cordis", - "corones", - "corpora", - "corporales", - "corporalis", - "corporalium", - "corpore", - "corpori", - "corporis", - "corporum", - "corpulentum", - "corpus", - "corrigebat", - "corrigendam", - "corruptelarum", - "corruptible", - "corruptione", - "coruscasti", - "cotidiana", - "cotidianam", - "cotidianas", - "cotidianum", - "cotidie", - "crapula", - "creator", - "creatorem", - "creaturam", - "crebro", - "credendum", - "credentium", - "credidi", - "credimus", - "credit", - "credita", - "creditarum", - "credituri", - "credunt", - "crucis", - "cubile", - "cubilia", - "cui", - "cuius", - "cuiuscemodi", - "cuiuslibet", - "cuiusquam", - "cuiusque", - "cum", - "cuncta", - "cupiant", - "cupidatatium", - "cupiditas", - "cupiditate", - "cupiditatem", - "cupiditatis", - "cupientem", - "cupimus", - "cupio", - "cupiunt", - "cur", - "cura", - "curam", - "curare", - "curiosa", - "curiosarum", - "curiositas", - "curiositate", - "curiositatis", - "curiosum", - "curo", - "currentem", - "custodiant", - "custodis", - "da", - "dabis", - "damnante", - "damnetur", - "dare", - "dari", - "das", - "datur", - "david", - "daviticum", - "de", - "debeo", - "debet", - "debui", - "deceptum", - "decernam", - "decet", - "deciperentur", - "decus", - "dedisti", - "deerat", - "deerit", - "defectus", - "defenditur", - "defluximus", - "deformis", - "defrito", - "defuissent", - "dei", - "deinde", - "delectamur", - "delectarentur", - "delectari", - "delectat", - "delectati", - "delectatio", - "delectatione", - "delectationem", - "delectatur", - "delectatus", - "delector", - "delet", - "deliciae", - "deliciosas", - "delicta", - "dementia", - "demerguntur", - "demetimur", - "demonstrare", - "demonstrasti", - "demonstrata", - "demonstratus", - "denuo", - "deo", - "depereunt", - "deponamus", - "depromi", - "deputabimus", - "des", - "deserens", - "deseri", - "desiderans", - "desiderant", - "desideraris", - "desiderata", - "desideravit", - "desiderem", - "desideriis", - "desiderio", - "desiderium", - "desidero", - "desidiosum", - "desivero", - "desperare", - "desperarem", - "desperatione", - "despiciam", - "destruas", - "desuper", - "det", - "deterior", - "deteriore", - "detestetur", - "detestor", - "detruncata", - "deum", - "deus", - "deviare", - "dextera", - "dexteram", - "diabolus", - "dicam", - "dicant", - "dicat", - "dicatur", - "dicebam", - "dicens", - "dicentem", - "dicentia", - "dicentium", - "dicere", - "dicerem", - "diceremus", - "dicerentur", - "diceretur", - "dici", - "dicimur", - "dicimus", - "dicis", - "dicit", - "dicite", - "dico", - "dictis", - "dictum", - "dicturus", - "dicunt", - "dicuntur", - "didicerim", - "didici", - "didicisse", - "didicissem", - "die", - "diebus", - "diei", - "diem", - "differens", - "difficultates", - "difficultatis", - "difiniendo", - "digna", - "dignaris", - "dignationem", - "dignatus", - "digni", - "dignitatibus", - "dignitatis", - "diiudicas", - "diiudico", - "dilabuntur", - "dilexisti", - "diligentius", - "diligi", - "diligit", - "dimensionumque", - "dimitti", - "dinoscens", - "dinumerans", - "direxi", - "discendi", - "discere", - "discerem", - "discerent", - "discernebat", - "discernens", - "discernere", - "discernerem", - "discernitur", - "discerno", - "discrevisse", - "discurro", - "dispensator", - "dispersione", - "displiceant", - "displicens", - "displicent", - "displiceo", - "displicere", - "dispulerim", - "disputandi", - "disputando", - "disputante", - "disputantur", - "disputare", - "dissentire", - "disseritur", - "dissimile", - "dissimilia", - "distantia", - "distincte", - "distinguere", - "distorta", - "diu", - "diutius", - "divellit", - "diversa", - "diversisque", - "diversitate", - "diverso", - "divexas", - "dividendo", - "divino", - "divitiae", - "dixeris", - "dixerit", - "dixi", - "dixit", - "doce", - "docebat", - "docens", - "docentem", - "doces", - "doctrinae", - "doctrinis", - "docuisti", - "doleam", - "doleamus", - "doleat", - "dolendum", - "dolet", - "dolor", - "dolore", - "dolorem", - "dolores", - "domi", - "dominaris", - "domine", - "domino", - "dominos", - "dominum", - "dominus", - "dona", - "donasti", - "donec", - "donum", - "dormiat", - "dormienti", - "dormientis", - "dormies", - "dormitabis", - "drachmam", - "duabus", - "dubia", - "dubitant", - "dubitatione", - "ducere", - "dulce", - "dulcedine", - "dulcedinem", - "dulcedo", - "dulces", - "dulcidine", - "dulcis", - "dum", - "duobus", - "dura", - "durum", - "duxi", - "e", - "ea", - "eadem", - "eam", - "eant", - "earum", - "eas", - "ebrietas", - "ebrietate", - "ebriosos", - "ebriosus", - "ecce", - "ecclesia", - "ecclesiae", - "edacitas", - "edendi", - "edendo", - "edunt", - "efficeret", - "egenus", - "egerim", - "ego", - "ei", - "eis", - "eius", - "elapsum", - "elati", - "elian", - "eligam", - "eliqua", - "eloquentes", - "eloquentiam", - "eloquia", - "eloquio", - "eloquiorum", - "emendicata", - "en", - "enervandam", - "enim", - "enubiletur", - "enumerat", - "eo", - "eodem", - "eoque", - "eorum", - "eos", - "eosdem", - "episcopo", - "equus", - "eram", - "erant", - "eras", - "erat", - "ergo", - "ergone", - "erigo", - "eripe", - "eripietur", - "eris", - "erit", - "erogo", - "errans", - "erro", - "erubescam", - "eruens", - "eruerentur", - "eruuntur", - "es", - "esau", - "esca", - "escae", - "escam", - "escas", - "esse", - "essem", - "essent", - "esset", - "est", - "estis", - "esto", - "esurio", - "et", - "etiam", - "etiamne", - "etiamsi", - "etsi", - "euge", - "eum", - "eundem", - "eunt", - "evacuaret", - "evellas", - "evellere", - "evelles", - "eventa", - "evidentius", - "evigilantes", - "evigilet", - "ex", - "exarsi", - "exaudi", - "excellentiam", - "exciderat", - "exciderunt", - "excipiens", - "excitant", - "excitentur", - "exclamaverunt", - "excogitanda", - "excusatio", - "excusationis", - "exemplo", - "exhibentur", - "exhorreas", - "existimet", - "exitum", - "expavi", - "expedita", - "experiamur", - "experiendi", - "experientia", - "experientiam", - "experimentum", - "experimur", - "experta", - "expertarum", - "expertum", - "expertus", - "expetuntur", - "explorandi", - "explorant", - "exsecror", - "exserentes", - "exteriora", - "exterioris", - "exteriorum", - "exterius", - "exterminantes", - "extinguere", - "extingueris", - "extra", - "extraneus", - "extrinsecus", - "exultans", - "exultatione", - "fabricasti", - "fabricatae", - "fabricationibus", - "fabricavit", - "fabrorum", - "fac", - "facere", - "faciam", - "faciant", - "faciat", - "facie", - "faciebat", - "faciei", - "faciem", - "faciendo", - "faciens", - "faciente", - "facies", - "faciet", - "facile", - "faciliter", - "facio", - "facis", - "facit", - "faciunt", - "facta", - "facti", - "factis", - "factito", - "factos", - "factum", - "factumque", - "factus", - "facultas", - "fallacia", - "fallaciam", - "fallar", - "fallax", - "fallere", - "falli", - "fallit", - "fallitur", - "falsa", - "falsi", - "falsis", - "falsissime", - "falsitate", - "falsum", - "fama", - "fames", - "familiari", - "familiaritate", - "famulatum", - "fastu", - "fatemur", - "fateor", - "febris", - "fecisse", - "fecisti", - "fecit", - "ferre", - "fiant", - "fias", - "fiat", - "fide", - "fidei", - "fidelis", - "fidem", - "fiducia", - "fierem", - "fierent", - "fieret", - "fieri", - "figmentis", - "filiis", - "filio", - "filiorum", - "filios", - "filium", - "filum", - "fine", - "finis", - "firma", - "fit", - "fixit", - "flabiles", - "flagitabat", - "flagitantur", - "flammam", - "flatus", - "flenda", - "flendae", - "fleo", - "flete", - "fletur", - "fletus", - "flexu", - "florum", - "fluctuo", - "fluctus", - "flumina", - "fluminum", - "fluxum", - "foeda", - "foras", - "fores", - "foribus", - "foris", - "forma", - "formaeque", - "formas", - "formosa", - "fornax", - "forsitan", - "fortasse", - "fortassis", - "forte", - "fortitudinem", - "fortius", - "fragrasti", - "frangat", - "fraternae", - "fraternis", - "fraternus", - "fratres", - "fratribus", - "freni", - "frequentatur", - "frigidique", - "frigidumve", - "fructu", - "fructum", - "fructus", - "fudi", - "fueram", - "fueramus", - "fuerim", - "fuerimus", - "fueris", - "fuerit", - "fuero", - "fuerunt", - "fugam", - "fugasti", - "fugiamus", - "fui", - "fuimus", - "fuisse", - "fuit", - "fulgeat", - "fulget", - "fundamenta", - "fundum", - "furens", - "futurae", - "futuras", - "futuri", - "gaudeam", - "gaudeant", - "gaudeat", - "gaudebit", - "gaudens", - "gaudent", - "gaudentes", - "gaudeo", - "gaudere", - "gaudet", - "gaudii", - "gaudiis", - "gaudio", - "gaudium", - "gavisum", - "gemitu", - "gemitum", - "gemitus", - "genera", - "generalis", - "generatimque", - "genere", - "generibus", - "generis", - "genuit", - "genus", - "gerit", - "geritur", - "gero", - "gestat", - "gloria", - "gloriae", - "gloriatur", - "gradibus", - "graeca", - "graecae", - "graece", - "graeci", - "graecus", - "grandi", - "grandis", - "gratia", - "gratiae", - "gratiam", - "gratiarum", - "gratias", - "gratis", - "grave", - "graventur", - "gressum", - "grex", - "gusta", - "gustandi", - "gustando", - "gustatae", - "gustavi", - "gutture", - "gutturis", - "gyros", - "habeas", - "habeat", - "habeatur", - "habebunt", - "habemus", - "habendum", - "habens", - "habent", - "habere", - "haberent", - "haberet", - "habes", - "habet", - "habitaculum", - "habitare", - "habitaret", - "habitas", - "habites", - "habiti", - "habito", - "hac", - "hae", - "haec", - "haeream", - "haereo", - "haeret", - "hanc", - "has", - "haurimus", - "haustum", - "hebesco", - "heremo", - "hi", - "hic", - "hierusalem", - "hilarescit", - "hinc", - "his", - "hoc", - "homine", - "hominem", - "homines", - "homini", - "hominibus", - "hominis", - "hominum", - "homo", - "honestis", - "honoris", - "horrendum", - "horum", - "hos", - "huc", - "huic", - "huius", - "huiuscemodi", - "humana", - "humanae", - "humanus", - "humilem", - "humilibus", - "humilitatem", - "hymno", - "hymnum", - "hymnus", - "iaceat", - "iacitur", - "iacob", - "iactantia", - "iacto", - "iam", - "iamque", - "ianua", - "ianuas", - "ibi", - "id", - "idem", - "ideo", - "ideoque", - "idoneus", - "ieiuniis", - "iesus", - "igitur", - "ignorat", - "illa", - "illac", - "illae", - "illam", - "ille", - "illi", - "illic", - "illico", - "illinc", - "illis", - "illius", - "illo", - "illos", - "illuc", - "illud", - "illum", - "imaginatur", - "imagine", - "imaginem", - "imagines", - "imaginesque", - "imaginibus", - "imaginis", - "imaginum", - "imago", - "imitanti", - "immaniter", - "immensa", - "immo", - "immortalis", - "imnagines", - "imperas", - "imperasti", - "imperfecta", - "impium", - "imples", - "imposuit", - "impressum", - "imprimi", - "imprimitur", - "improbat", - "improbet", - "in", - "inaequaliter", - "inanescunt", - "incaute", - "incertum", - "incertus", - "incideram", - "inciderunt", - "incipio", - "inclinatione", - "incognitam", - "incolis", - "incommutabilis", - "incomprehensibilis", - "inconcussus", - "inconsummatus", - "incorruptione", - "incurrunt", - "indagabit", - "inde", - "indecens", - "indica", - "indicabo", - "indicat", - "indicatae", - "indicavi", - "indidem", - "indigentiae", - "indigentiam", - "indisposite", - "indueris", - "ineffabiles", - "inesse", - "inest", - "inexcusabiles", - "inexplicabilis", - "infelix", - "inferiora", - "inferiore", - "infinita", - "infinitum", - "infirma", - "infirmior", - "infirmitas", - "infirmitate", - "infirmitatem", - "infirmitati", - "infirmitatis", - "infirmos", - "infirmus", - "infligi", - "influxit", - "ingemescentem", - "ingentes", - "ingenti", - "ingentibus", - "ingerantur", - "ingesta", - "ingredior", - "ingressae", - "ingressus", - "inhaerere", - "inhaereri", - "inhaeseram", - "inhaesero", - "inhiant", - "inimicus", - "iniqua", - "iniquitate", - "iniquitatibus", - "iniquitatis", - "iniuste", - "inlaqueantur", - "inlecebra", - "inlecebras", - "inlecebris", - "inlecebrosa", - "inlexit", - "inludi", - "inluminatio", - "inlusio", - "inlusionibus", - "inlustratori", - "inmemor", - "inmensa", - "inmoderatius", - "inmortalem", - "inmortali", - "inmunditiam", - "innecto", - "innocentia", - "innotescunt", - "innumerabiles", - "innumerabilia", - "innumerabilibus", - "innumerabiliter", - "innumerabilium", - "inperfectum", - "inperitiam", - "inperturbata", - "inpiis", - "inpinguandum", - "inpiorum", - "inplicans", - "inplicaverant", - "inplicentur", - "inpressa", - "inpressas", - "inpressit", - "inprobari", - "inquit", - "inquiunt", - "inretractabilem", - "inruebam", - "inruentes", - "inruentibus", - "insania", - "insaniam", - "insidiarum", - "insidiatur", - "insidiis", - "insinuat", - "inspirationis", - "instat", - "instituta", - "instituti", - "integer", - "intellecta", - "intellectus", - "intellegentis", - "intellegimus", - "intellegitur", - "intellego", - "intellegunt", - "intellexisse", - "intendere", - "intendimus", - "intentio", - "intentioni", - "intentionis", - "intentum", - "intentus", - "inter", - "interdum", - "interest", - "interfui", - "interior", - "interiora", - "interiore", - "interioris", - "interius", - "interiusque", - "interpellante", - "interpellat", - "interponunt", - "interrogans", - "interrogantibus", - "interrogare", - "interrogarentur", - "interrogari", - "interrogatio", - "interrogavi", - "interrogem", - "interroges", - "interroget", - "interrogo", - "interrumpunt", - "interrumpuntur", - "interstitio", - "intervalla", - "intervallis", - "intime", - "intonas", - "intra", - "intrant", - "intraverint", - "intraverunt", - "intravi", - "intrinsecus", - "intromittis", - "intromittuntur", - "introrsus", - "intuerer", - "intuetur", - "intus", - "inusitatum", - "invectarum", - "inveni", - "inveniam", - "inveniebam", - "invenimus", - "invenio", - "invenirem", - "inveniremus", - "inveniret", - "invenisse", - "invenit", - "inventa", - "inventor", - "inventum", - "inventus", - "invidentes", - "invisibiles", - "invisibilia", - "invocari", - "invoco", - "iohannem", - "ioseph", - "ipsa", - "ipsae", - "ipsam", - "ipsaque", - "ipsarum", - "ipsas", - "ipse", - "ipsi", - "ipsis", - "ipsius", - "ipso", - "ipsos", - "ipsosque", - "ipsum", - "israel", - "issac", - "ista", - "istae", - "istam", - "istarum", - "istas", - "iste", - "isti", - "istis", - "isto", - "istorum", - "istuc", - "istum", - "ita", - "itaque", - "item", - "iterum", - "itidem", - "iube", - "iubens", - "iubentem", - "iubentis", - "iubes", - "iucundiora", - "iucunditas", - "iudex", - "iudicante", - "iudicanti", - "iudicantibus", - "iudicare", - "iudicet", - "iudicia", - "iugo", - "iumenti", - "iussisti", - "iustificas", - "iustificatorum", - "iustitiae", - "iustitiam", - "iustum", - "iustus", - "labamur", - "labor", - "laboribus", - "laboro", - "lacrimas", - "laetamur", - "laetandis", - "laetatum", - "laetatus", - "laetitia", - "laetitiae", - "laetitiam", - "laetus", - "laetusque", - "languidus", - "languor", - "languores", - "laniato", - "lapidem", - "lapsus", - "laqueis", - "laqueo", - "laqueus", - "lascivos", - "lassitudines", - "lata", - "lateant", - "lateat", - "latere", - "latet", - "latina", - "latinae", - "latine", - "latinique", - "latis", - "latissimos", - "latitabant", - "laudabunt", - "laudandum", - "laudantur", - "laudare", - "laudari", - "laudatio", - "laudatorem", - "laudatur", - "laudatus", - "laudavit", - "laude", - "laudem", - "laudes", - "laudibus", - "laudis", - "laudor", - "lectorem", - "lege", - "leges", - "leguntur", - "lene", - "lenia", - "lenticulae", - "leporem", - "leve", - "levia", - "libeat", - "libeatque", - "libenter", - "liber", - "liberalibus", - "liberamenta", - "liberasti", - "libet", - "libidine", - "libro", - "licet", - "liliorum", - "lineas", - "lingua", - "linguarum", - "liquida", - "liquide", - "litteras", - "litteratura", - "loca", - "loco", - "locorum", - "locum", - "locuntur", - "locus", - "locutum", - "locutus", - "longe", - "longius", - "longum", - "loquebar", - "loquendo", - "loquens", - "loqueremur", - "loqueretur", - "loquitur", - "loquor", - "lucem", - "lucente", - "lucentem", - "lucerna", - "lucet", - "lucis", - "lucustis", - "lugens", - "lumen", - "luminibus", - "luminoso", - "lunam", - "lustravi", - "lux", - "machinationibus", - "macula", - "maerere", - "maerore", - "maerores", - "maeroribus", - "maestitiae", - "magicas", - "magis", - "magisque", - "magistro", - "magna", - "magnam", - "magni", - "magnificet", - "magnifico", - "magnum", - "magnus", - "maior", - "mala", - "male", - "mali", - "malim", - "malint", - "malis", - "malitia", - "malle", - "mallem", - "malo", - "malorum", - "malum", - "malus", - "mandamus", - "manducandi", - "manducantem", - "manducare", - "manducat", - "manducaverimus", - "manduco", - "maneas", - "manes", - "manet", - "manifesta", - "manifestari", - "manifestet", - "manifestetur", - "manifestus", - "manna", - "mansuefecisti", - "manu", - "manum", - "manus", - "mare", - "maris", - "mavult", - "maxime", - "me", - "mea", - "meae", - "meam", - "mearum", - "meas", - "mecum", - "mediator", - "mediatorem", - "medicamenta", - "medice", - "medicina", - "medicus", - "meditatusque", - "meditor", - "medium", - "medius", - "mei", - "meis", - "mel", - "melior", - "meliore", - "meliores", - "melius", - "mella", - "melodias", - "melos", - "membra", - "memento", - "meminerim", - "meminerimus", - "meminerunt", - "memini", - "meminimus", - "meminisse", - "meminissem", - "meminissemus", - "meminit", - "memor", - "memores", - "memoria", - "memoriae", - "memoriam", - "memoriter", - "mendacio", - "mendacium", - "mentem", - "mentiatur", - "mentiri", - "mentitur", - "meo", - "meorum", - "meos", - "meque", - "meretur", - "meridies", - "meritatem", - "meritis", - "merito", - "meruit", - "metas", - "metuebam", - "metuimus", - "metum", - "metumve", - "meum", - "meus", - "mihi", - "miles", - "militare", - "minister", - "ministerium", - "minor", - "minora", - "minuendo", - "minuit", - "minus", - "minusve", - "minutissimis", - "mira", - "mirabili", - "mirabilia", - "mirabiliter", - "miracula", - "mirandum", - "mirantur", - "mirari", - "mirifica", - "mirificum", - "miris", - "mirum", - "miser", - "misera", - "miserabiliter", - "miseratione", - "misereberis", - "miserere", - "miseria", - "miseriae", - "misericordia", - "misericordiae", - "misericordiam", - "misericordias", - "misericorditer", - "misericors", - "miseros", - "misertus", - "misisti", - "mittere", - "moderationi", - "moderatum", - "modestis", - "modi", - "modico", - "modicum", - "modis", - "modo", - "modos", - "modulatione", - "modum", - "modus", - "mole", - "molem", - "moles", - "molesta", - "molestia", - "molestiam", - "molestias", - "molestum", - "molle", - "momentum", - "montes", - "montium", - "monuisti", - "morbo", - "mordeor", - "mors", - "mortales", - "mortalis", - "mortalitatis", - "mortaliter", - "mortem", - "mortilitate", - "mortui", - "mortuis", - "mortuus", - "motus", - "moveat", - "movent", - "moveor", - "moveri", - "mulier", - "multa", - "multi", - "multimoda", - "multimodo", - "multiplices", - "multiplicitas", - "multiplicius", - "multique", - "multis", - "multos", - "multum", - "mulus", - "munda", - "mundatior", - "mundi", - "mundis", - "mundum", - "munera", - "munere", - "munerum", - "murmuravit", - "muscas", - "muta", - "mutans", - "mutant", - "mutare", - "mutaveris", - "mystice", - "nam", - "nares", - "narium", - "narrantes", - "narro", - "nascendo", - "nati", - "natura", - "naturae", - "naturam", - "ne", - "nec", - "necant", - "necessaria", - "necessarium", - "necesse", - "necessitas", - "necessitatis", - "neglecta", - "negotium", - "neminem", - "nemo", - "nepotibus", - "nequaquam", - "neque", - "nequeunt", - "nesciam", - "nesciat", - "nesciebam", - "nescio", - "nescirem", - "nescit", - "nidosve", - "nigrum", - "nihil", - "nihilo", - "nihilque", - "nimia", - "nimii", - "nimirum", - "nimis", - "nisi", - "niteat", - "nitidos", - "nituntur", - "nobis", - "nocte", - "noe", - "nolentes", - "nolit", - "nolle", - "nollem", - "nollent", - "nolo", - "nolunt", - "nomen", - "nominamus", - "nominata", - "nominatur", - "nomine", - "nominis", - "nomino", - "nominum", - "non", - "nondum", - "nonne", - "nonnullius", - "nonnumquam", - "norunt", - "nos", - "noscendi", - "noscendique", - "noscendum", - "nosse", - "nossemus", - "nosti", - "nostra", - "nostrae", - "nostram", - "nostri", - "nostrique", - "nostros", - "nostrum", - "nota", - "notatum", - "notiones", - "notitia", - "notus", - "nova", - "noverit", - "noverunt", - "novi", - "novit", - "novum", - "nuda", - "nugatoriis", - "nulla", - "nullam", - "nullo", - "nullum", - "num", - "numeramus", - "numerans", - "numerorum", - "numeros", - "numquam", - "numquid", - "nunc", - "nuntiantibus", - "nuntiata", - "nuntiavimus", - "nuntiavit", - "nuntii", - "nuntios", - "nusquam", - "nutantibus", - "nutu", - "o", - "ob", - "oblectamenta", - "oblectandi", - "obliti", - "oblitos", - "oblitum", - "oblitumque", - "oblitus", - "oblivio", - "oblivionem", - "oblivionis", - "obliviscamur", - "obliviscar", - "oblivisceremur", - "obliviscimur", - "oboritur", - "obruitur", - "obsecro", - "obsonii", - "obtentu", - "obumbret", - "occideris", - "occulta", - "occulto", - "occultum", - "occupantur", - "occurrant", - "occurrat", - "occurrerit", - "occurrit", - "occurro", - "occursantur", - "oceani", - "oceanum", - "oculi", - "oculis", - "oculo", - "oculorum", - "oculos", - "oculum", - "oculus", - "oderunt", - "odium", - "odor", - "odoratus", - "odore", - "odorem", - "odores", - "odorum", - "offendamus", - "offensionem", - "offeratur", - "offeretur", - "officia", - "officiis", - "officium", - "oleat", - "olefac", - "olent", - "olet", - "oleum", - "olfaciens", - "olfactum", - "olorem", - "oluerunt", - "omne", - "omnem", - "omnes", - "omnesque", - "omni", - "omnia", - "omnibus", - "omnimodarum", - "omnino", - "omnipotens", - "omnipotenti", - "omnis", - "omnium", - "oneri", - "operata", - "operatores", - "opertis", - "operum", - "opibus", - "opificiis", - "oportebat", - "oportere", - "oportet", - "optare", - "optimus", - "opus", - "orantibus", - "orare", - "oraremus", - "orationes", - "oraturis", - "ordinatorem", - "ore", - "oris", - "os", - "ostentet", - "pacem", - "pacto", - "paene", - "palleant", - "palliata", - "palpa", - "pane", - "paratus", - "parit", - "pars", - "parte", - "partes", - "parum", - "parva", - "parvulus", - "parvus", - "passim", - "passionis", - "passionum", - "pater", - "pati", - "patienter", - "patitur", - "patriam", - "patrocinium", - "paucis", - "paulatim", - "pauper", - "paupertatem", - "pax", - "peccare", - "peccati", - "peccatis", - "peccato", - "peccator", - "peccatores", - "peccatoris", - "peccatorum", - "peccatum", - "peccavit", - "pecco", - "pecora", - "pectora", - "pede", - "pedes", - "pedisequa", - "pelluntur", - "pendenda", - "penetrale", - "penetralia", - "penetro", - "penitus", - "penuriam", - "pepercisti", - "per", - "peragravi", - "percepta", - "percipitur", - "percurro", - "percussisti", - "perdiderat", - "perdit", - "perdita", - "perdite", - "perditum", - "peregrinor", - "peregrinorum", - "perfecturum", - "perficiatur", - "perfundens", - "perfusus", - "pergo", - "periculis", - "periculo", - "periculorum", - "periculosa", - "periculosissimam", - "periculum", - "perierat", - "perit", - "peritia", - "permanens", - "permanentes", - "permissum", - "perpetret", - "perscrutanda", - "persentiscere", - "persequi", - "persuadeant", - "persuaserit", - "pertendam", - "pertinet", - "pertractans", - "perturbant", - "perturbatione", - "perturbationes", - "perturbor", - "pervenire", - "pervenit", - "perversa", - "perversae", - "peste", - "petam", - "petat", - "petimus", - "petitur", - "piae", - "piam", - "picturis", - "pietatis", - "pius", - "placeam", - "placeant", - "placent", - "placentes", - "placere", - "places", - "placet", - "placuit", - "plagas", - "plangendae", - "plena", - "plenariam", - "plenas", - "plenis", - "pleno", - "plenus", - "plerumque", - "pluris", - "plus", - "poenaliter", - "pollutum", - "ponamus", - "pondere", - "ponderibus", - "ponendi", - "ponere", - "populi", - "populus", - "porro", - "portat", - "porto", - "posco", - "poscuntur", - "posita", - "positus", - "posse", - "possem", - "possemus", - "possent", - "posside", - "possideas", - "possidere", - "possideri", - "possim", - "possimus", - "possint", - "possit", - "possum", - "possumus", - "possunt", - "post", - "postea", - "posterior", - "potens", - "potentias", - "poterimus", - "poterunt", - "potes", - "potest", - "potestatem", - "potestates", - "potius", - "potu", - "potuere", - "potuero", - "potui", - "potuimus", - "potuit", - "prae", - "praebens", - "praebeo", - "praecedentia", - "praecedentium", - "praecidere", - "praeciderim", - "praeciditur", - "praeciperet", - "praecurrere", - "praedicans", - "praeditum", - "praegravatis", - "praeibat", - "praeire", - "praeiret", - "praeparat", - "praeposita", - "praesentes", - "praesentia", - "praesentiam", - "praesentior", - "praesidens", - "praesidenti", - "praesides", - "praesignata", - "praestabis", - "praestat", - "praesto", - "praetende", - "praeter", - "praeterierit", - "praeterita", - "praeteritae", - "praeteritam", - "praeteritis", - "praeteritorum", - "praeteritum", - "praetoria", - "prece", - "pretium", - "primatum", - "primitus", - "primo", - "primordiis", - "primus", - "principes", - "pristinae", - "pristinum", - "prius", - "priusquam", - "privatam", - "privatio", - "pro", - "probet", - "procedens", - "proceditur", - "procedunt", - "processura", - "prodeat", - "prodest", - "prodeunt", - "prodigia", - "proferatur", - "proferens", - "profero", - "proferrem", - "proferuntur", - "profunda", - "prohibuisti", - "proiectus", - "promisisti", - "promissio", - "pronuntianti", - "propinquius", - "propitius", - "proponatur", - "propositi", - "propria", - "proprie", - "proprios", - "propter", - "propterea", - "prorsus", - "proruunt", - "prosiliunt", - "prospera", - "prosperis", - "prosperitatibus", - "prosperitatis", - "prout", - "provectu", - "proximi", - "proximum", - "psalmi", - "psalterium", - "pugno", - "pulchra", - "pulchras", - "pulchris", - "pulchritudine", - "pulchritudinis", - "pulchritudinum", - "pulchritudo", - "pulsant", - "pulsatori", - "pulvere", - "pulvis", - "purgarentur", - "pusilla", - "pusillus", - "putant", - "putare", - "putem", - "qua", - "quadam", - "quadrupedibus", - "quae", - "quaecumque", - "quaedam", - "quaeque", - "quaeram", - "quaeratur", - "quaere", - "quaerebam", - "quaerebant", - "quaerebatur", - "quaerens", - "quaerentes", - "quaerere", - "quaererem", - "quaerimus", - "quaeris", - "quaerit", - "quaeritur", - "quaero", - "quaerunt", - "quaesisse", - "quaesitionum", - "quaesiveram", - "quaesivit", - "quaeso", - "quaestio", - "quaestionum", - "quale", - "qualibus", - "qualis", - "qualiscumque", - "quam", - "quamdiu", - "quamquam", - "quamvis", - "quandam", - "quando", - "quandoquidem", - "quanta", - "quanti", - "quantis", - "quanto", - "quantulum", - "quantum", - "quare", - "quarum", - "quas", - "quasi", - "quattuor", - "quem", - "quemadmodum", - "quendam", - "qui", - "quia", - "quibus", - "quibusdam", - "quibusve", - "quicquam", - "quicumque", - "quid", - "quidam", - "quidem", - "quidquid", - "quiescente", - "quietem", - "quippe", - "quis", - "quisquam", - "quisque", - "quisquis", - "quo", - "quocirca", - "quocumque", - "quod", - "quodam", - "quomodo", - "quoniam", - "quoque", - "quoquo", - "quorum", - "quos", - "quot", - "quotiens", - "quousque", - "radiavit", - "radios", - "rapiatur", - "rapinam", - "rapit", - "rapiunt", - "raptae", - "ratio", - "rationes", - "rationi", - "re", - "rebellis", - "rebus", - "reccido", - "recedat", - "recedimus", - "receptaculis", - "recessus", - "recipit", - "recognoscimus", - "recognoscitur", - "recognovi", - "recolenda", - "recolere", - "recolerentur", - "recoleretur", - "recolo", - "reconcilearet", - "reconciliare", - "recondens", - "recondi", - "recondidi", - "reconditae", - "reconditum", - "recondo", - "recordabor", - "recordando", - "recordans", - "recordantes", - "recordarer", - "recordationem", - "recordationis", - "recordemur", - "recordentur", - "recorder", - "recordor", - "recti", - "recuperatae", - "redarguentem", - "reddatur", - "reddi", - "redditur", - "redducet", - "redeamus", - "redemit", - "redigens", - "redigimur", - "redimas", - "redire", - "refectum", - "refero", - "referrem", - "reficiatur", - "reficimus", - "refrenare", - "refugio", - "refulges", - "regem", - "regina", - "regio", - "rei", - "relaxari", - "relaxatione", - "religione", - "religiosius", - "relinquentes", - "relinquunt", - "reliquerim", - "rem", - "reminiscendo", - "reminiscente", - "reminiscenti", - "reminiscentis", - "reminiscerer", - "reminisci", - "reminiscimur", - "reminiscor", - "remisisti", - "remota", - "remotiora", - "remotum", - "removeri", - "renuntiabant", - "repente", - "repercussus", - "reperiamus", - "reperio", - "reperiret", - "reperta", - "repetamus", - "repeterent", - "repleo", - "reponens", - "reponuntur", - "repositi", - "repositum", - "reprehensum", - "reptilia", - "requiem", - "requies", - "requiramus", - "requiratur", - "requiro", - "requirunt", - "requiruntur", - "rerum", - "res", - "resistere", - "resistimus", - "resistis", - "resistit", - "resisto", - "resolvisti", - "resorbeor", - "respice", - "respiciens", - "respirent", - "respondeat", - "respondent", - "responderent", - "responderunt", - "respondes", - "respondi", - "respondit", - "responsa", - "responsio", - "responsionibus", - "respuimus", - "respuitur", - "respuo", - "restat", - "retarder", - "retenta", - "retibus", - "retinemus", - "retinetur", - "retinuit", - "retractanda", - "retractarem", - "retractarentur", - "retractatur", - "retranseo", - "retribuet", - "retrusa", - "rideat", - "ridentem", - "ridiculum", - "rogantem", - "rogeris", - "rogo", - "ruga", - "ruinas", - "ruminando", - "rupisti", - "rursus", - "rutilet", - "sacerdos", - "sacramenta", - "sacramenti", - "sacramentis", - "sacramento", - "sacrificatori", - "sacrificium", - "sacrifico", - "sacrilega", - "saeculi", - "saeculum", - "saepe", - "saepius", - "salubritatis", - "salus", - "salute", - "salutem", - "saluti", - "salutis", - "salvi", - "salvus", - "sana", - "sanabis", - "sanare", - "sanari", - "sanas", - "sanaturi", - "sanctae", - "sancte", - "sancti", - "sanctis", - "sanctuarium", - "sane", - "sanes", - "sanguine", - "sanum", - "sapere", - "sapiat", - "sapida", - "sapientiae", - "sapientiorem", - "sapit", - "sapor", - "sapores", - "sarcina", - "sat", - "satago", - "saties", - "satietas", - "satietate", - "satietatis", - "satis", - "saturantur", - "saturari", - "saucio", - "saucium", - "sciam", - "scientiae", - "scierim", - "scio", - "scire", - "scirem", - "scirent", - "sciret", - "sciri", - "scis", - "scit", - "sciunt", - "scribentur", - "scrutamur", - "se", - "secreta", - "secreti", - "secreto", - "sectantur", - "sectatores", - "sectatur", - "secum", - "secundum", - "secura", - "securior", - "securus", - "sed", - "sedem", - "sedentem", - "sedet", - "sedibus", - "seducam", - "seductionibus", - "semel", - "semper", - "sempiterna", - "senectute", - "sensarum", - "sensibus", - "sensifico", - "sensis", - "sensu", - "sensum", - "sensus", - "sensusque", - "sententia", - "sententiam", - "sententiis", - "sentiebat", - "sentiens", - "sentientem", - "sentio", - "sentire", - "sentitur", - "sentiunt", - "seorsum", - "separatum", - "separavit", - "sepelivit", - "sequatur", - "sequentes", - "sequi", - "sequitur", - "serie", - "sermo", - "sero", - "servata", - "servi", - "serviam", - "serviant", - "serviendo", - "servientes", - "servirent", - "servis", - "servitutem", - "serviunt", - "servo", - "sese", - "seu", - "severitate", - "si", - "sibi", - "sibimet", - "sic", - "sicubi", - "sicut", - "sicuti", - "sidera", - "siderum", - "signa", - "significantur", - "significaret", - "significat", - "significationem", - "significatur", - "signum", - "silente", - "silentio", - "silva", - "sim", - "simile", - "similes", - "similia", - "similis", - "similitudine", - "similitudinem", - "similitudines", - "simillimum", - "simplicem", - "simul", - "simulque", - "simus", - "sine", - "singillatim", - "singula", - "sinis", - "sint", - "sinu", - "sinus", - "sit", - "sitio", - "sitis", - "sive", - "sobrios", - "socialiter", - "socias", - "societatis", - "sociorum", - "sola", - "solae", - "solam", - "solebat", - "solem", - "solet", - "soli", - "solis", - "solitis", - "solitudinem", - "solo", - "solum", - "solus", - "somnis", - "somno", - "sonant", - "sonare", - "sonaret", - "sonat", - "sonet", - "soni", - "sonis", - "sono", - "sonorum", - "sonos", - "sonuerit", - "sonuerunt", - "sonum", - "sonus", - "sopitur", - "soporem", - "soporis", - "spargant", - "spargens", - "spargit", - "sparsa", - "sparsis", - "spatiatus", - "spatiis", - "spe", - "speciem", - "species", - "spectaculis", - "spectandum", - "specto", - "speculum", - "spem", - "sperans", - "spernat", - "spes", - "spiritum", - "spiritus", - "splendeat", - "splendorem", - "splenduisti", - "stat", - "statim", - "statuit", - "stelio", - "stellas", - "stet", - "stilo", - "stipendium", - "strepitu", - "stupor", - "sua", - "suae", - "suam", - "suarum", - "suaveolentiam", - "suavi", - "suavia", - "suavis", - "suavitas", - "suavitatem", - "suavium", - "sub", - "subdita", - "subditi", - "subditus", - "subduntur", - "subeundam", - "subinde", - "subintrat", - "subire", - "subiugaverant", - "sublevas", - "subrepsit", - "subsidium", - "subtrahatur", - "succurrat", - "sudoris", - "sufficiat", - "sufficiens", - "suffragatio", - "suffragia", - "suggeruntur", - "suggestionibus", - "suggestionum", - "sui", - "suis", - "sum", - "sumendi", - "sumpturus", - "sumus", - "sunt", - "suo", - "super", - "superbam", - "superbi", - "superbia", - "superbiae", - "superbiam", - "superbis", - "superindui", - "supervacuanea", - "suppetat", - "supplicii", - "supra", - "surdis", - "surditatem", - "surgam", - "surgere", - "suspensus", - "suspirat", - "suspirent", - "sustinere", - "tacet", - "tacite", - "tactus", - "tale", - "tali", - "talia", - "talibus", - "talium", - "tam", - "tamdiu", - "tamen", - "tamenetsi", - "tametsi", - "tamquam", - "tandem", - "tangendo", - "tangunt", - "tanta", - "tantarum", - "tanto", - "tantulum", - "tantum", - "te", - "tecum", - "tegitur", - "temperata", - "templi", - "tempore", - "temporis", - "temporum", - "temptamur", - "temptandi", - "temptari", - "temptat", - "temptatio", - "temptatione", - "temptationem", - "temptationes", - "temptationibus", - "temptationis", - "temptationum", - "temptatum", - "temptatur", - "temptaverunt", - "temptetur", - "tempus", - "tenacius", - "teneam", - "teneant", - "teneat", - "tenebant", - "tenebatur", - "tenebrae", - "tenebris", - "tenebrosi", - "tenendi", - "tenent", - "teneo", - "teneor", - "teneretur", - "teneri", - "tenet", - "tenetur", - "tenuissimas", - "tenuiter", - "teque", - "terra", - "terrae", - "terram", - "tertio", - "tertium", - "testibus", - "testis", - "tetigi", - "tetigisti", - "texisti", - "theatra", - "thesauri", - "thesauro", - "thesaurus", - "tibi", - "timeamur", - "timent", - "timeo", - "timere", - "timeri", - "timore", - "timuisse", - "tobis", - "toleramus", - "tolerantiam", - "tolerare", - "tolerari", - "tolerat", - "toleret", - "tot", - "tota", - "totiens", - "totis", - "totius", - "toto", - "totum", - "tradidisti", - "trahunt", - "traicit", - "traiecta", - "transactam", - "transcendi", - "transeam", - "transeatur", - "transeo", - "transfigurans", - "transgredientibus", - "transibo", - "transierunt", - "transire", - "transisse", - "transit", - "transitu", - "transitus", - "tremore", - "tremorem", - "tria", - "tribuere", - "tribuis", - "triplici", - "tristis", - "tristitia", - "tristitiam", - "trium", - "tu", - "tua", - "tuae", - "tuam", - "tuas", - "tuetur", - "tui", - "tuis", - "tum", - "tunc", - "tundentes", - "tuo", - "tuorum", - "tuos", - "turbantur", - "turibulis", - "turpibus", - "turpis", - "turpitudines", - "tutiusque", - "tutor", - "tutum", - "tuum", - "tuus", - "typho", - "ubi", - "ubique", - "ubiubi", - "ulla", - "ullis", - "ullo", - "ulterius", - "umbrarum", - "umquam", - "una", - "unde", - "undique", - "ungentorum", - "unico", - "unicus", - "universus", - "unum", - "unus", - "urunt", - "uspiam", - "usque", - "usui", - "usum", - "usurpant", - "ut", - "utcumque", - "utendi", - "uterque", - "utilitate", - "utilitatem", - "utimur", - "utinam", - "utique", - "utrique", - "utriusque", - "utroque", - "utrubique", - "utrum", - "utrumque", - "vae", - "valde", - "valeam", - "valeant", - "valent", - "valentes", - "valeo", - "valerem", - "valerent", - "valeret", - "vales", - "valet", - "valetudinis", - "valida", - "vana", - "vanae", - "vanescit", - "vanias", - "vanitatem", - "vanitatis", - "vanus", - "varia", - "variando", - "varias", - "variis", - "vasis", - "vegetas", - "vehementer", - "vel", - "velim", - "velint", - "velit", - "velle", - "vellem", - "vellemus", - "vellent", - "velut", - "veluti", - "venatio", - "veni", - "venio", - "venit", - "veniunt", - "venter", - "ventos", - "ventre", - "ventrem", - "ventris", - "vera", - "verae", - "verax", - "verba", - "verbis", - "verbo", - "verborum", - "verbum", - "vere", - "veris", - "veritas", - "veritate", - "veritatem", - "vero", - "verum", - "verus", - "vestibus", - "vestigio", - "vestra", - "vetare", - "vi", - "via", - "viae", - "viam", - "vicinior", - "vicit", - "victima", - "victor", - "victoria", - "victoriam", - "vide", - "videam", - "videant", - "videat", - "videbam", - "videbat", - "videmus", - "videndi", - "videndo", - "videns", - "vident", - "video", - "videor", - "videre", - "viderem", - "videri", - "viderunt", - "vides", - "videt", - "videtur", - "vidi", - "vigilans", - "vigilantem", - "vigilantes", - "vigilanti", - "vim", - "vindicandi", - "vindicavit", - "violari", - "violis", - "viribus", - "virtus", - "vis", - "visa", - "visco", - "visione", - "visionum", - "vita", - "vitae", - "vitaliter", - "vitam", - "vituperante", - "vituperare", - "vituperari", - "vituperatio", - "vituperetur", - "viva", - "vivam", - "vivant", - "vivarum", - "vivat", - "vivendum", - "vivente", - "viventis", - "vivere", - "vivifico", - "vivit", - "vivunt", - "vix", - "vobiscum", - "vocant", - "vocantes", - "vocantur", - "vocasti", - "vocatur", - "voce", - "vocem", - "vocibus", - "vocis", - "volatibus", - "volebant", - "volens", - "volito", - "volo", - "voluerit", - "voluero", - "volui", - "voluisti", - "voluit", - "volumus", - "volunt", - "voluntas", - "voluntate", - "voluptaria", - "voluptas", - "voluptate", - "voluptatem", - "voluptates", - "voluptatibus", - "voluptatis", - "voluptatum", - "volvere", - "vos", - "vox", - "vulnera", - "vult", - "vultu", -} diff --git a/util/fake/location.go b/util/fake/location.go deleted file mode 100644 index dadc5f42..00000000 --- a/util/fake/location.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "fmt" - "strings" -) - -var names = []string{"Home", "Work", "Business", "Personal"} - -var streets = []string{"Avenue", "Boulevard", "Center", "Circle", "Court", "Drive", "Extension", "Glen", "Grove", "Heights", "Highway", "Junction", "Key", "Lane", "Loop", "Manor", "Mill", "Park", "Parkway", "Pass", "Path", "Pike", "Place", "Plaza", "Point", "Ridge", "River", "Road", "Square", "Street", "Terrace", "Trail", "Turnpike", "View", "Way"} - -var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"} - -var counties = []string{"Bath and North East Somerset", "Aberdeenshire", "Anglesey", "Angus", "Bedford", "Blackburn with Darwen", "Blackpool", "Bournemouth", "Bracknell Forest", "Brighton & Hove", "Bristol", "Buckinghamshire", "Cambridgeshire", "Carmarthenshire", "Central Bedfordshire", "Ceredigion", "Cheshire East", "Cheshire West and Chester", "Clackmannanshire", "Conwy", "Cornwall", "County Antrim", "County Armagh", "County Down", "County Durham", "County Fermanagh", "County Londonderry", "County Tyrone", "Cumbria", "Darlington", "Denbighshire", "Derby", "Derbyshire", "Devon", "Dorset", "Dumfries and Galloway", "Dundee", "East Lothian", "East Riding of Yorkshire", "East Sussex", "Edinburgh", "Essex", "Falkirk", "Fife", "Flintshire", "Gloucestershire", "Greater London", "Greater Manchester", "Gwent", "Gwynedd", "Halton", "Hampshire", "Hartlepool", "Herefordshire", "Hertfordshire", "Highlands", "Hull", "Isle of Wight", "Isles of Scilly", "Kent", "Lancashire", "Leicester", "Leicestershire", "Lincolnshire", "Lothian", "Luton", "Medway", "Merseyside", "Mid Glamorgan", "Middlesbrough", "Milton Keynes", "Monmouthshire", "Moray", "Norfolk", "North East Lincolnshire", "North Lincolnshire", "North Somerset", "North Yorkshire", "Northamptonshire", "Northumberland", "Nottingham", "Nottinghamshire", "Oxfordshire", "Pembrokeshire", "Perth and Kinross", "Peterborough", "Plymouth", "Poole", "Portsmouth", "Powys", "Reading", "Redcar and Cleveland", "Rutland", "Scottish Borders", "Shropshire", "Slough", "Somerset", "South Glamorgan", "South Gloucestershire", "South Yorkshire", "Southampton", "Southend-on-Sea", "Staffordshire", "Stirlingshire", "Stockton-on-Tees", "Stoke-on-Trent", "Strathclyde", "Suffolk", "Surrey", "Swindon", "Telford and Wrekin", "Thurrock", "Torbay", "Tyne and Wear", "Warrington", "Warwickshire", "West Berkshire", "West Glamorgan", "West Lothian", "West Midlands", "West Sussex", "West Yorkshire", "Western Isles", "Wiltshire", "Windsor and Maidenhead", "Wokingham", "Worcestershire", "Wrexham", "York"} - -var countries = []string{"Afghanistan", "Åland Islands", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua & Barbuda", "Argentina", "Armenia", "Aruba", "Ascension Island", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil", "British Indian Ocean Territory", "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Canary Islands", "Cape Verde", "Caribbean Netherlands", "Cayman Islands", "Central African Republic", "Ceuta & Melilla", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo - Brazzaville", "Congo - Kinshasa", "Cook Islands", "Costa Rica", "Côte d'Ivoire", "Croatia", "Cuba", "Curaçao", "Cyprus", "Czech Republic", "Denmark", "Diego Garcia", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong SAR China", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau SAR China", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar (Burma)", "Namibia", "Nauru", "Nepal", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestinian Territories", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", "Réunion", "Romania", "Russia", "Rwanda", "Samoa", "San Marino", "São Tomé and Príncipe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia & South Sandwich Islands", "South Korea", "South Sudan", "Spain", "Sri Lanka", "St. Barthélemy", "St. Helena", "St. Kitts & Nevis", "St. Lucia", "St. Martin", "St. Pierre & Miquelon", "St. Vincent & Grenadines", "Sudan", "Suriname", "Svalbard & Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad & Tobago", "Tristan da Cunha", "Tunisia", "Turkey", "Turkmenistan", "Turks & Caicos Islands", "Tuvalu", "U.S. Outlying Islands", "U.S. Virgin Islands", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis & Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe"} - -func LocationName() string { - return New().LocationName() -} - -func (f *Faker) LocationName() string { - return names[f.r.Intn(len(names))] -} - -func LocationAddress() string { - return New().LocationAddress() -} - -func (f *Faker) LocationAddress() string { - return fmt.Sprintf("%d %s", - f.IntegerBetween(1, 250), - f.LocationStreet(), - ) -} - -func LocationStreet() string { - return New().LocationStreet() -} - -func (f *Faker) LocationStreet() string { - return fmt.Sprintf("%s %s", - strings.Title(f.Word()), - streets[f.r.Intn(len(streets))], - ) -} - -func LocationCity() string { - return New().LocationCity() -} - -func (f *Faker) LocationCity() string { - return strings.Title(f.Word()) -} - -func LocationState() string { - return New().LocationState() -} - -func (f *Faker) LocationState() string { - return states[f.r.Intn(len(states))] -} - -func LocationCounty() string { - return New().LocationCounty() -} - -func (f *Faker) LocationCounty() string { - return counties[f.r.Intn(len(counties))] -} - -func LocationZipcode() string { - return New().LocationZipcode() -} - -func (f *Faker) LocationZipcode() string { - return fmt.Sprintf("%s%s %d", - f.CharUpper(), - f.CharUpper(), - f.IntegerBetween(10000, 99999), - ) -} - -func LocationPostcode() string { - return New().LocationPostcode() -} - -func (f *Faker) LocationPostcode() string { - return fmt.Sprintf("%s%s%d %d%s%s", - f.CharUpper(), - f.CharUpper(), - f.IntegerBetween(0, 20), - f.IntegerBetween(0, 99), - f.CharUpper(), - f.CharUpper(), - ) -} - -func LocationCountry() string { - return New().LocationCountry() -} - -func (f *Faker) LocationCountry() string { - return countries[f.r.Intn(len(countries))] -} - -func LocationAltitude() float64 { - return New().LocationAltitude() -} - -func (f *Faker) LocationAltitude() float64 { - return f.r.Float64() * 8848 -} - -func LocationLatitude() float64 { - return New().LocationLatitude() -} - -func (f *Faker) LocationLatitude() float64 { - return f.r.Float64()*180 - 90 -} - -func LocationLongitude() float64 { - return New().LocationLongitude() -} - -func (f *Faker) LocationLongitude() float64 { - return f.r.Float64()*360 - 180 -} diff --git a/util/fake/lorem.go b/util/fake/lorem.go deleted file mode 100644 index 52fa3cf7..00000000 --- a/util/fake/lorem.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "strings" -) - -func (f *Faker) rand() int { - r := f.r.Float32() * 100 - switch { - case r < 1.939: - return 1 - case r < 19.01: - return 2 - case r < 38.00: - return 3 - case r < 50.41: - return 4 - case r < 61.00: - return 5 - case r < 70.09: - return 6 - case r < 78.97: - return 7 - case r < 85.65: - return 8 - case r < 90.87: - return 9 - case r < 95.05: - return 10 - case r < 97.27: - return 11 - case r < 98.67: - return 12 - case r < 100.0: - return 13 - } - return 2 -} - -func (f *Faker) word(size int) string { - if size < 1 { - size = 1 - } - if size > 13 { - size = 13 - } - for n := f.r.Int() % len(latin); ; n++ { - if n >= len(latin)-1 { - n = 0 - } - if len(latin[n]) == size { - return latin[n] - } - } - return "" -} - -func Lorem() string { - return New().Lorem() -} - -func (f *Faker) Lorem() string { - return f.word(f.IntegerBetween(4, 13)) -} - -func Sentence() string { - return New().Sentence() -} - -func (f *Faker) Sentence() string { - return f.SentenceBetween(5, 22) -} - -func SentenceBetween(beg, end int) string { - return New().SentenceBetween(beg, end) -} - -func (f *Faker) SentenceBetween(beg, end int) string { - s := f.IntegerBetween(beg, end) - w := []string{} - for i, c := 0, 0; i < s; i++ { - if i == 0 { - w = append(w, strings.Title(f.word(f.rand()))) - } else { - w = append(w, f.word(f.rand())) - } - if c >= 2 || i <= 2 || i >= s-1 { - continue - } - if f.r.Int()%s == 0 { - w[i-1] += "," - c++ - } - } - return strings.Join(w, " ") + "." -} - -func Paragraph() string { - return New().Paragraph() -} - -func (f *Faker) Paragraph() string { - return f.ParagraphBetween(3, 7) -} - -func ParagraphBetween(beg, end int) string { - return New().ParagraphBetween(beg, end) -} - -func (f *Faker) ParagraphBetween(beg, end int) string { - w := []string{} - for i := 0; i < f.IntegerBetween(beg, end); i++ { - w = append(w, f.Sentence()) - } - return strings.Join(w, " ") -} diff --git a/util/fake/number.go b/util/fake/number.go deleted file mode 100644 index b565bd05..00000000 --- a/util/fake/number.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -func Integer() int { - return New().Integer() -} - -func (f *Faker) Integer() int { - return f.r.Int() -} - -func IntegerBetween(beg, end int) int { - return New().IntegerBetween(beg, end) -} - -func (f *Faker) IntegerBetween(beg, end int) int { - return f.r.Intn(end-beg) + beg -} - -func Decimal() float64 { - return New().Decimal() -} - -func (f *Faker) Decimal() float64 { - return f.r.NormFloat64() -} - -func DecimalBetween(beg, end float64) float64 { - return New().DecimalBetween(beg, end) -} - -func (f *Faker) DecimalBetween(beg, end float64) float64 { - return f.r.Float64()*(end-beg) + beg -} diff --git a/util/fake/person.go b/util/fake/person.go deleted file mode 100644 index 5a49f93d..00000000 --- a/util/fake/person.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "fmt" - "strings" -) - -var gender = []string{"Male", "Female"} - -var male = []string{"James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "George", "Donald", "Anthony", "Paul", "Mark", "Edward", "Steven", "Kenneth", "Andrew", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Frank", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Jonathan", "Scott", "Raymond", "Justin", "Brandon", "Gregory", "Samuel", "Benjamin", "Patrick", "Jack", "Henry", "Walter", "Dennis", "Jerry", "Alexander", "Peter", "Tyler", "Douglas", "Harold", "Aaron", "Jose", "Adam", "Arthur", "Zachary", "Carl", "Nathan", "Albert", "Kyle", "Lawrence", "Joe", "Willie", "Gerald", "Roger", "Keith", "Jeremy", "Terry", "Harry", "Ralph", "Sean", "Jesse", "Roy", "Louis", "Billy", "Austin", "Bruce", "Eugene", "Christian", "Bryan", "Wayne", "Russell", "Howard", "Fred", "Ethan", "Jordan", "Philip", "Alan", "Juan", "Randy", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Victor", "Clarence", "Ernest", "Martin", "Craig", "Stanley", "Shawn", "Travis", "Bradley", "Leonard", "Earl", "Gabriel", "Jimmy", "Francis", "Todd", "Noah", "Danny", "Dale", "Cody", "Carlos", "Allen", "Frederick", "Logan", "Curtis", "Alex", "Joel", "Luis", "Norman", "Marvin", "Glenn", "Tony", "Nathaniel", "Rodney", "Melvin", "Alfred", "Steve", "Cameron", "Chad", "Edwin", "Caleb", "Evan", "Antonio", "Lee", "Herbert", "Jeffery", "Isaac", "Derek", "Ricky", "Marcus", "Theodore", "Elijah", "Luke", "Jesus", "Eddie", "Troy", "Mike", "Dustin", "Ray", "Adrian", "Bernard", "Leroy", "Angel", "Randall", "Wesley", "Ian", "Jared", "Mason", "Hunter", "Calvin", "Oscar", "Clifford", "Jay", "Shane", "Ronnie", "Barry", "Lucas", "Corey", "Manuel", "Leo", "Tommy", "Warren", "Jackson", "Isaiah", "Connor", "Don", "Dean", "Jon", "Julian", "Miguel", "Bill", "Lloyd", "Charlie", "Mitchell", "Leon", "Jerome", "Darrell", "Jeremiah", "Alvin", "Brett", "Seth", "Floyd", "Jim", "Blake", "Micheal", "Gordon", "Trevor", "Lewis", "Erik", "Edgar", "Vernon", "Devin", "Gavin", "Jayden", "Chris", "Clyde", "Tom", "Derrick", "Mario", "Brent", "Marc", "Herman", "Chase", "Dominic", "Ricardo", "Franklin", "Maurice", "Max", "Aiden", "Owen", "Lester", "Gilbert", "Elmer", "Gene", "Francisco", "Glen", "Cory", "Garrett", "Clayton", "Sam", "Jorge", "Chester", "Alejandro", "Jeff", "Harvey", "Milton", "Cole", "Ivan", "Andre", "Duane", "Landon"} - -var female = []string{"Mary", "Emma", "Elizabeth", "Minnie", "Margaret", "Ida", "Alice", "Bertha", "Sarah", "Annie", "Clara", "Ella", "Florence", "Cora", "Martha", "Laura", "Nellie", "Grace", "Carrie", "Maude", "Mabel", "Bessie", "Jennie", "Gertrude", "Julia", "Hattie", "Edith", "Mattie", "Rose", "Catherine", "Lillian", "Ada", "Lillie", "Helen", "Jessie", "Louise", "Ethel", "Lula", "Myrtle", "Eva", "Frances", "Lena", "Lucy", "Edna", "Maggie", "Pearl", "Daisy", "Fannie", "Josephine", "Dora", "Rosa", "Katherine", "Agnes", "Marie", "Nora", "May", "Mamie", "Blanche", "Stella", "Ellen", "Nancy", "Effie", "Sallie", "Nettie", "Della", "Lizzie", "Flora", "Susie", "Maud", "Mae", "Etta", "Harriet", "Sadie", "Caroline", "Katie", "Lydia", "Elsie", "Kate", "Susan", "Mollie", "Alma", "Addie", "Georgia", "Eliza", "Lulu", "Nannie", "Lottie", "Amanda", "Belle", "Charlotte", "Rebecca", "Ruth", "Viola", "Olive", "Amelia", "Hannah", "Jane", "Virginia", "Emily", "Matilda", "Irene", "Kathryn", "Esther", "Willie", "Henrietta", "Ollie", "Amy", "Rachel", "Sara", "Estella", "Theresa", "Augusta", "Ora", "Pauline", "Josie", "Lola", "Sophia", "Leona", "Anne", "Mildred", "Ann", "Beulah", "Callie", "Lou", "Delia", "Eleanor", "Barbara", "Iva", "Louisa", "Maria", "Mayme", "Evelyn", "Estelle", "Nina", "Betty", "Marion", "Bettie", "Dorothy", "Luella", "Inez", "Lela", "Rosie", "Allie", "Millie", "Janie", "Cornelia", "Victoria", "Ruby", "Winifred", "Alta", "Celia", "Christine", "Beatrice", "Birdie", "Harriett", "Mable", "Myra", "Sophie", "Tillie", "Isabel", "Sylvia", "Carolyn", "Isabelle", "Leila", "Sally", "Ina", "Essie", "Bertie", "Nell", "Alberta", "Katharine", "Lora", "Rena", "Mina", "Rhoda", "Mathilda", "Abbie", "Eula", "Dollie", "Hettie", "Eunice", "Fanny", "Ola", "Lenora", "Adelaide", "Christina", "Lelia", "Nelle", "Sue", "Johanna", "Lilly", "Lucinda", "Minerva", "Lettie", "Roxie", "Cynthia", "Helena", "Hilda", "Hulda", "Bernice", "Genevieve", "Jean", "Cordelia", "Marian", "Francis", "Jeanette", "Adeline", "Gussie", "Leah", "Lois", "Lura", "Mittie", "Hallie", "Isabella", "Olga", "Phoebe", "Teresa", "Hester", "Lida", "Lina", "Winnie", "Claudia", "Marguerite", "Vera", "Cecelia", "Bess", "Emilie", "Rosetta", "Verna", "Myrtie", "Cecilia", "Elva", "Olivia", "Ophelia", "Georgie", "Elnora", "Violet", "Adele", "Lily", "Linnie", "Loretta", "Madge", "Polly", "Virgie", "Eugenia", "Lucile", "Lucille", "Mabelle", "Rosalie"} - -var surnames = []string{"Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson", "Clark", "Rodriguez", "Lewis", "Lee", "Walker", "Hall", "Allen", "Young", "Hernandez", "King", "Wright", "Lopez", "Hill", "Scott", "Green", "Adams", "Baker", "Gonzalez", "Nelson", "Carter", "Mitchell", "Perez", "Roberts", "Turner", "Phillips", "Campbell", "Parker", "Evans", "Edwards", "Collins", "Stewart", "Sanchez", "Morris", "Rogers", "Reed", "Cook", "Morgan", "Bell", "Murphy", "Bailey", "Rivera", "Cooper", "Richardson", "Cox", "Howard", "Ward", "Torres", "Peterson", "Gray", "Ramirez", "James", "Watson", "Brooks", "Kelly", "Sanders", "Price", "Bennett", "Wood", "Barnes", "Ross", "Henderson", "Coleman", "Jenkins", "Perry", "Powell", "Long", "Patterson", "Hughes", "Flores", "Washington", "Butler", "Simmons", "Foster", "Gonzales", "Bryant", "Alexander", "Russell", "Griffin", "Diaz", "Hayes", "Myers", "Ford", "Hamilton", "Graham", "Sullivan", "Wallace", "Woods", "Cole", "West", "Jordan", "Owens", "Reynolds", "Fisher", "Ellis", "Harrison", "Gibson", "McDonald", "Cruz", "Marshall", "Ortiz", "Gomez", "Murray", "Freeman", "Wells", "Webb", "Simpson", "Stevens", "Tucker", "Porter", "Hunter", "Hicks", "Crawford", "Henry", "Boyd", "Mason", "Morales", "Kennedy", "Warren", "Dixon", "Ramos", "Reyes", "Burns", "Gordon", "Shaw", "Holmes", "Rice", "Robertson", "Hunt", "Black", "Daniels", "Palmer", "Mills", "Nichols", "Grant", "Knight", "Ferguson", "Rose", "Stone", "Hawkins", "Dunn", "Perkins", "Hudson", "Spencer", "Gardner", "Stephens", "Payne", "Pierce", "Berry", "Matthews", "Arnold", "Wagner", "Willis", "Ray", "Watkins", "Olson", "Carroll", "Duncan", "Snyder", "Hart", "Cunningham", "Bradley", "Lane", "Andrews", "Ruiz", "Harper", "Fox", "Riley", "Armstrong", "Carpenter", "Weaver", "Greene", "Lawrence", "Elliott", "Chavez", "Sims", "Austin", "Peters", "Kelley", "Franklin", "Lawson", "Fields", "Gutierrez", "Ryan", "Schmidt", "Carr", "Vasquez", "Castillo", "Wheeler", "Chapman", "Oliver", "Montgomery", "Richards", "Williamson", "Johnston", "Banks", "Meyer", "Bishop", "McCoy", "Howell", "Alvarez", "Morrison", "Hansen", "Fernandez", "Garza", "Harvey", "Little", "Burton", "Stanley", "Nguyen", "George", "Jacobs", "Reid", "Kim", "Fuller", "Lynch", "Dean", "Gilbert", "Garrett", "Romero", "Welch", "Larson", "Frazier", "Burke", "Hanson", "Day", "Mendoza", "Moreno", "Bowman", "Medina", "Fowler", "Brewer", "Hoffman", "Carlson", "Silva", "Pearson", "Holland", "Douglas", "Fleming", "Jensen", "Vargas", "Byrd", "Davidson", "Hopkins", "May", "Terry", "Herrera", "Wade", "Soto", "Walters", "Curtis", "Neal", "Caldwell", "Lowe", "Jennings", "Barnett", "Graves", "Jimenez", "Horton", "Shelton", "Barrett", "Obrien", "Castro", "Sutton", "Gregory", "McKinney", "Lucas", "Miles", "Craig", "Rodriquez", "Chambers", "Holt", "Lambert", "Fletcher", "Watts", "Bates", "Hale", "Rhodes", "Pena", "Beck", "Newman", "Haynes", "McDaniel", "Mendez", "Bush", "Vaughn", "Parks", "Dawson", "Santiago", "Norris", "Hardy", "Love", "Steele", "Curry", "Powers", "Schultz", "Barker", "Guzman", "Page", "Munoz", "Ball", "Keller", "Chandler", "Weber", "Leonard", "Walsh", "Lyons", "Ramsey", "Wolfe", "Schneider", "Mullins", "Benson", "Sharp", "Bowen", "Daniel", "Barber", "Cummings", "Hines", "Baldwin", "Griffith", "Valdez", "Hubbard", "Salazar", "Reeves", "Warner", "Stevenson", "Burgess", "Santos", "Tate", "Cross", "Garner", "Mann", "Mack", "Moss", "Thornton", "Dennis", "McGee", "Farmer", "Delgado", "Aguilar", "Vega", "Glover", "Manning", "Cohen", "Harmon", "Rodgers", "Robbins", "Newton", "Todd", "Blair", "Higgins", "Ingram", "Reese", "Cannon", "Strickland", "Townsend", "Potter", "Goodwin", "Walton", "Rowe", "Hampton", "Ortega", "Patton", "Swanson", "Joseph", "Francis", "Goodman", "Maldonado", "Yates", "Becker", "Erickson", "Hodges", "Rios", "Conner", "Adkins", "Webster", "Norman", "Malone", "Hammond", "Flowers", "Cobb", "Moody", "Quinn", "Blake", "Maxwell", "Pope", "Floyd", "Osborne", "Paul", "McCarthy", "Guerrero", "Lindsey", "Estrada", "Sandoval", "Gibbs", "Tyler", "Gross", "Fitzgerald", "Stokes", "Doyle", "Sherman", "Saunders", "Wise", "Colon", "Gill", "Alvarado", "Greer", "Padilla", "Simon", "Waters", "Nunez", "Ballard", "Schwartz", "McBride", "Houston", "Christensen", "Klein", "Pratt", "Briggs", "Parsons", "McLaughlin", "Zimmerman", "French", "Buchanan", "Moran", "Copeland", "Roy", "Pittman", "Brady", "McCormick", "Holloway", "Brock", "Poole", "Frank", "Logan", "Owen", "Bass", "Marsh", "Drake", "Wong", "Jefferson", "Park", "Morton", "Abbott", "Sparks", "Patrick", "Norton", "Huff", "Clayton", "Massey", "Lloyd", "Figueroa", "Carson", "Bowers", "Roberson", "Barton", "Tran", "Lamb", "Harrington", "Casey", "Boone", "Cortez", "Clarke", "Mathis", "Singleton", "Wilkins", "Cain", "Bryan", "Underwood", "Hogan", "McKenzie", "Collier", "Luna", "Phelps", "McGuire", "Allison", "Bridges", "Wilkerson", "Nash", "Summers", "Atkins"} - -var jobtitles = []string{"Airline Pilot", "Academic Team", "Accountant", "Account Executive", "Actor", "Actuary", "Acquisition Analyst", "Administrative Asst.", "Administrative Analyst", "Administrator", "Advertising Director", "Aerospace Engineer", "Agent", "Agricultural Inspector", "Agricultural Scientist", "Air Traffic Controller", "Animal Trainer", "Anthropologist", "Appraiser", "Architect", "Art Director", "Artist", "Astronomer", "Athletic Coach", "Auditor", "Author", "Baker", "Banker", "Bankruptcy Attorney", "Benefits Manager", "Biologist", "Bio-feedback Specialist", "Biomedical Engineer", "Biotechnical Researcher", "Broadcaster", "Broker", "Building Manager", "Building Contractor", "Building Inspector", "Business Analyst", "Business Planner", "Business Manager", "Buyer", "Call Center Manager", "Career Counselor", "Cash Manager", "Ceramic Engineer", "Chief Executive Officer", "Chief Operation Officer", "Chef", "Chemical Engineer", "Chemist", "Child Care Manager", "Chief Medical Officer", "Chiropractor", "Cinematographer", "City Housing Manager", "City Manager", "Civil Engineer", "Claims Manager", "Clinical Research Assistant", "Collections Manager.", "Compliance Manager", "Comptroller", "Computer Manager", "Commercial Artist", "Communications Affairs Director", "Communications Director", "Communications Engineer", "Compensation Analyst", "Computer Programmer", "Computer Ops. Manager", "Computer Engineer", "Computer Operator", "Computer Graphics Specialist", "Construction Engineer", "Construction Manager", "Consultant", "Consumer Relations Manager", "Contract Administrator", "Copyright Attorney", "Copywriter", "Corporate Planner", "Corrections Officer", "Cosmetologist", "Credit Analyst", "Cruise Director", "Chief Information Officer", "Chief Technology Officer", "Customer Service Manager", "Cryptologist", "Dancer", "Data Security Manager", "Database Manager", "Day Care Instructor", "Dentist", "Designer", "Design Engineer", "Desktop Publisher", "Developer", "Development Officer", "Diamond Merchant", "Dietitian", "Direct Marketer", "Director", "Distribution Manager", "Diversity Manager", "Economist", "EEO Compliance Manager", "Editor", "Education Adminator", "Electrical Engineer", "Electro Optical Engineer", "Electronics Engineer", "Embassy Management", "Employment Agent", "Engineer Technician", "Entrepreneur", "Environmental Analyst", "Environmental Attorney", "Environmental Engineer", "Environmental Specialist", "Escrow Officer", "Estimator", "Executive Assistant", "Executive Director", "Executive Recruiter", "Facilities Manager", "Family Counselor", "Fashion Events Manager", "Fashion Merchandiser", "Fast Food Manager", "Film Producer", "Film Production Assistant", "Financial Analyst", "Financial Planner", "Financier", "Fine Artist", "Wildlife Specialist", "Fitness Consultant", "Flight Attendant", "Flight Engineer", "Floral Designer", "Food & Beverage Director", "Food Service Manager", "Forestry Technician", "Franchise Management", "Franchise Sales", "Fraud Investigator", "Freelance Writer", "Fund Raiser", "General Manager", "Geologist", "General Counsel", "Geriatric Specialist", "Gerontologist", "Glamour Photographer", "Golf Club Manager", "Gourmet Chef", "Graphic Designer", "Grounds Keeper", "Hazardous Waste Manager", "Health Care Manager", "Health Therapist", "Health Service Administrator", "Hearing Officer", "Home Economist", "Horticulturist", "Hospital Administrator", "Hotel Manager", "Human Resources Manager", "Importer", "Industrial Designer", "Industrial Engineer", "Information Director", "Inside Sales", "Insurance Adjuster", "Interior Decorator", "Internal Controls Director", "International Acct.", "International Courier", "International Lawyer", "Interpreter", "Investigator", "Investment Banker", "Investment Manager", "IT Architect", "IT Project Manager", "IT Systems Analyst", "Jeweler", "Joint Venture Manager", "Journalist", "Labor Negotiator", "Labor Organizer", "Labor Relations Manager", "Lab Services Director", "Lab Technician", "Land Developer", "Landscape Architect", "Law Enforcement Officer", "Lawyer", "Lead Software Engineer", "Lead Software Test Engineer", "Leasing Manager", "Legal Secretary", "Library Manager", "Litigation Attorney", "Loan Officer", "Lobbyist", "Logistics Manager", "Maintenance Manager", "Management Consultant", "Managed Care Director", "Managing Partner", "Manufacturing Director", "Manpower Planner", "Marine Biologist", "Market Res. Analyst", "Marketing Director", "Materials Manager", "Mathematician", "Membership Chairman", "Mechanic", "Mechanical Engineer", "Media Buyer", "Medical Investor", "Medical Secretary", "Medical Technician", "Mental Health Counselor", "Merchandiser", "Metallurgical Engineering", "Meteorologist", "Microbiologist", "MIS Manager", "Motion Picture Director", "Multimedia Director", "Musician", "Network Administrator", "Network Specialist", "Network Operator", "New Product Manager", "Novelist", "Nuclear Engineer", "Nuclear Specialist", "Nutritionist", "Nursing Administrator", "Occupational Therapist", "Oceanographer", "Office Manager", "Operations Manager", "Operations Research Director", "Optical Technician", "Optometrist", "Organizational Development Manager", "Outplacement Specialist", "Paralegal", "Park Ranger", "Patent Attorney", "Payroll Specialist", "Personnel Specialist", "Petroleum Engineer", "Pharmacist", "Photographer", "Physical Therapist", "Physician", "Physician Assistant", "Physicist", "Planning Director", "Podiatrist", "Political Analyst", "Political Scientist", "Politician", "Portfolio Manager", "Preschool Management", "Preschool Teacher", "Principal", "Private Banker", "Private Investigator", "Probation Officer", "Process Engineer", "Producer", "Product Manager", "Product Engineer", "Production Engineer", "Production Planner", "Professional Athlete", "Professional Coach", "Professor", "Project Engineer", "Project Manager", "Program Manager", "Property Manager", "Public Administrator", "Public Safety Director", "PR Specialist", "Publisher", "Purchasing Agent", "Publishing Director", "Quality Assurance Specialist", "Quality Control Engineer", "Quality Control Inspector", "Radiology Manager", "Railroad Engineer", "Real Estate Broker", "Recreational Director", "Recruiter", "Redevelopment Specialist", "Regulatory Affairs Manager", "Registered Nurse", "Rehabilitation Counselor", "Relocation Manager", "Reporter", "Research Specialist", "Restaurant Manager", "Retail Store Manager", "Risk Analyst", "Safety Engineer", "Sales Engineer", "Sales Trainer", "Sales Promotion Manager", "Sales Representative", "Sales Manager", "Service Manager", "Sanitation Engineer", "Scientific Programmer", "Scientific Writer", "Securities Analyst", "Security Consultant", "Security Director", "Seminar Presenter", "Ship's Officer", "Singer", "Social Director", "Social Program Planner", "Social Research", "Social Scientist", "Social Worker", "Sociologist", "Software Developer", "Software Engineer", "Software Test Engineer", "Soil Scientist", "Special Events Manager", "Special Education Teacher", "Special Projects Director", "Speech Pathologist", "Speech Writer", "Sports Event Manager", "Statistician", "Store Manager", "Strategic Alliance Director", "Strategic Planning Director", "Stress Reduction Specialist", "Stockbroker", "Surveyor", "Structural Engineer", "Superintendent", "Supply Chain Director", "System Engineer", "Systems Analyst", "Systems Programmer", "System Administrator", "Tax Specialist", "Teacher", "Technical Support Specialist", "Technical Illustrator", "Technical Writer", "Technology Director", "Telecom Analyst", "Telemarketer", "Theatrical Director", "Title Examiner", "Tour Escort", "Tour Guide Director", "Traffic Manager", "Trainer Translator", "Transportation Manager", "Travel Agent", "Treasurer", "TV Programmer", "Underwriter", "Union Representative", "University Administrator", "University Dean", "Urban Planner", "Veterinarian", "Vendor Relations Director", "Viticulturist", "Warehouse Manager"} - -func PersonEmail() string { - return New().PersonEmail() -} - -func (f *Faker) PersonEmail() string { - return fmt.Sprintf("%s.%s@%s", - strings.ToLower(f.PersonFirstname()), - strings.ToLower(f.PersonLastname()), - f.Domain(), - ) -} - -func PersonPhone() string { - return New().PersonPhone() -} - -func (f *Faker) PersonPhone() string { - return fmt.Sprintf("%05d %03d %03d", - f.IntegerBetween(0, 9999), - f.IntegerBetween(0, 999), - f.IntegerBetween(0, 999), - ) -} - -func PersonGender() string { - return New().PersonGender() -} - -func (f *Faker) PersonGender() string { - return gender[f.r.Intn(len(gender))] -} - -func PersonFullname() string { - return New().PersonFullname() -} - -func (f *Faker) PersonFullname() string { - return f.PersonFirstname() + " " + f.PersonLastname() -} - -func PersonFirstname() string { - return New().PersonFirstname() -} - -func (f *Faker) PersonFirstname() string { - switch 0.5 <= f.r.Float64() { - case true: - return male[f.r.Intn(len(male))] - case false: - return female[f.r.Intn(len(female))] - } - return "" -} - -func PersonLastname() string { - return New().PersonLastname() -} - -func (f *Faker) PersonLastname() string { - return surnames[f.r.Intn(len(surnames))] -} - -func PersonUsername() string { - return New().PersonUsername() -} - -func (f *Faker) PersonUsername() string { - return fmt.Sprintf("%s.%s%d", - strings.ToLower(f.PersonFirstname()), - strings.ToLower(f.PersonLastname()), - f.IntegerBetween(1, 999), - ) -} - -func PersonJobtitle() string { - return New().PersonJobtitle() -} - -func (f *Faker) PersonJobtitle() string { - return jobtitles[f.r.Intn(len(jobtitles))] -} diff --git a/util/fake/string.go b/util/fake/string.go deleted file mode 100644 index 8cc9dd29..00000000 --- a/util/fake/string.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "bytes" - "fmt" -) - -func String() string { - return New().String() -} - -func (f *Faker) String() string { - var b bytes.Buffer - for i := 0; i < f.IntegerBetween(1, 100); i++ { - b.WriteString(f.Alphanum()) - } - return b.String() -} - -func StringLength(size int) string { - return New().StringLength(size) -} - -func (f *Faker) StringLength(size int) string { - var b bytes.Buffer - for i := 0; i < size; i++ { - b.WriteString(f.Alphanum()) - } - return b.String() -} - -func StringBetween(beg, end int) string { - return New().StringBetween(beg, end) -} - -func (f *Faker) StringBetween(beg, end int) string { - var b bytes.Buffer - for i := 0; i < f.IntegerBetween(beg, end); i++ { - b.WriteString(f.Alphanum()) - } - return b.String() -} - -func Syllable() string { - return New().Syllable() -} - -func (f *Faker) Syllable() string { - if f.Bool() { - switch f.Bool() { - case true: - return fmt.Sprintf("%s%s", f.CharVowel(), f.CharConsonant()) - case false: - return fmt.Sprintf("%s%s", f.CharConsonant(), f.CharVowel()) - } - } - return fmt.Sprintf("%s%s%s", f.CharConsonant(), f.CharVowel(), f.CharConsonant()) -} - -func Word() string { - return New().Word() -} - -func (f *Faker) Word() string { - var str [4]string - for i := 0; i < 4; i++ { - str[i] = "" - } - for i := 0; i < f.IntegerBetween(2, 4); i++ { - str[i] = f.Syllable() - } - return fmt.Sprintf("%s%s%s%s", str[0], str[1], str[2], str[3]) -} diff --git a/util/fake/time.go b/util/fake/time.go deleted file mode 100644 index d4670e05..00000000 --- a/util/fake/time.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "math" - "time" -) - -func Time() time.Time { - return New().Time() -} - -func (f *Faker) Time() time.Time { - n := int64(f.IntegerBetween(0, math.MaxInt64)) - return time.Unix(0, n) -} - -func TimeBetween(beg, end time.Time) time.Time { - return New().TimeBetween(beg, end) -} -func (f *Faker) TimeBetween(beg, end time.Time) time.Time { - b := int(beg.UnixNano()) - e := int(end.UnixNano()) - n := int64(f.IntegerBetween(b, e)) - return time.Unix(0, n) -} diff --git a/util/fake/uuid.go b/util/fake/uuid.go deleted file mode 100644 index 5ebbf36f..00000000 --- a/util/fake/uuid.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "github.com/surrealdb/surrealdb/util/uuid" -) - -func Uuid() string { - return uuid.New().String() -} - -func (f *Faker) Uuid() string { - return uuid.New().String() -} diff --git a/util/fake/web.go b/util/fake/web.go deleted file mode 100644 index fa45e27a..00000000 --- a/util/fake/web.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fake - -import ( - "fmt" -) - -var tlds = []string{"com", "org", "edu", "gov", "co.uk", "net", "io", "ac", "ad", "ae", "af", "ag", "ai", "al", "am", "an", "ao", "aq", "ar", "as", "at", "au", "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "bq", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cu", "cv", "cw", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et", "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "ss", "st", "su", "sv", "sx", "sy", "sz", "tc", "td", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tp", "tr", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "ye", "yt", "za", "zm", "zw"} - -func Avatar() string { - return New().Avatar() -} - -func (f *Faker) Avatar() string { - return fmt.Sprintf("%s%s", - "https://www.gravatar.com/avatar/", - f.StringLength(32), - ) -} - -func Domain() string { - return New().Domain() -} - -func (f *Faker) Domain() string { - return f.Word() + "." + f.Tld() -} - -func Tld() string { - return New().Tld() -} - -func (f *Faker) Tld() string { - return tlds[f.r.Intn(len(tlds))] -} - -func Url() string { - return New().Url() -} - -func (f *Faker) Url() string { - return fmt.Sprintf("https://%s/%s/%s", - f.Domain(), - f.Word(), - f.Word(), - ) -} diff --git a/util/fncs/args.go b/util/fncs/args.go deleted file mode 100644 index 7e444aa8..00000000 --- a/util/fncs/args.go +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "fmt" - "math" - "strconv" - "time" - - "github.com/surrealdb/surrealdb/sql" -) - -var defaultTime = time.Unix(0, 0) - -func copySlice(arr []interface{}) (out []interface{}) { - out = make([]interface{}, len(arr)) - copy(out, arr) - return -} - -func outputFloat(val float64) (interface{}, error) { - switch { - case math.IsNaN(val): - return nil, nil - case math.IsInf(val, 0): - return nil, nil - default: - return val, nil - } -} - -func outputFixed(val float64, pre int64) (interface{}, error) { - out := math.Pow(10, float64(pre)) - rnd := int(val*out + math.Copysign(0.5, val*out)) - return float64(rnd) / out, nil -} - -func ensureString(val interface{}) (out string, ok bool) { - switch val := val.(type) { - case string: - return val, true - case nil: - return "", true - default: - return fmt.Sprint(val), true - } -} - -func ensureBytes(val interface{}) (out []byte, ok bool) { - switch val := val.(type) { - case []byte: - return val, true - case string: - return []byte(val), true - case nil: - return []byte(""), true - default: - return []byte(fmt.Sprint(val)), true - } -} - -func ensureBool(val interface{}) (out bool, ok bool) { - switch val := val.(type) { - case bool: - return val, true - case string: - if val, err := strconv.ParseBool(val); err == nil { - return val, true - } - } - return false, false -} - -func ensureInt(val interface{}) (out int64, ok bool) { - switch val := val.(type) { - case int: - return int64(val), true - case int64: - return int64(val), true - case uint: - return int64(val), true - case uint64: - return int64(val), true - case float32: - return int64(val), true - case float64: - return int64(val), true - case string: - if val, err := strconv.ParseFloat(val, 64); err == nil { - return int64(val), true - } - } - return 0, false -} - -func ensureFloat(val interface{}) (out float64, ok bool) { - switch val := val.(type) { - case int: - return float64(val), true - case int64: - return float64(val), true - case uint: - return float64(val), true - case uint64: - return float64(val), true - case float32: - return float64(val), true - case float64: - return float64(val), true - case string: - if val, err := strconv.ParseFloat(val, 64); err == nil { - return float64(val), true - } - } - return 0, false -} - -func ensureTime(val interface{}) (out time.Time, ok bool) { - switch val := val.(type) { - case time.Time: - return val, true - case string: - if val, err := time.Parse(time.RFC3339Nano, val); err == nil { - return val, true - } - } - return defaultTime, false -} - -func ensurePoint(val interface{}) (out *sql.Point, ok bool) { - switch val := val.(type) { - case *sql.Point: - return val, true - case []interface{}: - if p := ensureFloats(val); len(p) == 2 { - return sql.NewPoint(p[0], p[1]), true - } - } - return nil, false -} - -func ensureCircle(val interface{}) (out *sql.Circle, ok bool) { - switch val := val.(type) { - case *sql.Circle: - return val, true - } - return nil, false -} - -func ensurePolygon(val interface{}) (out *sql.Polygon, ok bool) { - switch val := val.(type) { - case *sql.Polygon: - return val, true - } - return nil, false -} - -func ensureGeometry(val interface{}) (out sql.Expr, ok bool) { - switch val := val.(type) { - case *sql.Point: - return val, true - case *sql.Circle: - return val, true - case *sql.Polygon: - return val, true - } - return nil, false -} - -func ensureDuration(val interface{}) (out time.Duration, ok bool) { - switch val := val.(type) { - case time.Duration: - return val, true - } - return 0, false -} - -func ensureSlice(args interface{}) (out []interface{}, ok bool) { - if i, ok := args.([]interface{}); ok { - return i, true - } else { - return []interface{}{args}, false - } -} - -func ensureObject(args interface{}) (out map[string]interface{}, ok bool) { - if i, ok := args.(map[string]interface{}); ok { - return i, true - } else { - return map[string]interface{}{}, false - } -} - -func ensureInts(args interface{}) (out []int64) { - arr, _ := ensureSlice(args) - for _, val := range arr { - switch val := val.(type) { - case int: - out = append(out, int64(val)) - case int64: - out = append(out, int64(val)) - case uint: - out = append(out, int64(val)) - case uint64: - out = append(out, int64(val)) - case float32: - out = append(out, int64(val)) - case float64: - out = append(out, int64(val)) - case string: - if val, err := strconv.ParseFloat(val, 64); err == nil { - out = append(out, int64(val)) - } - } - } - return -} - -func ensureFloats(args interface{}) (out []float64) { - arr, _ := ensureSlice(args) - for _, val := range arr { - switch val := val.(type) { - case int: - out = append(out, float64(val)) - case int64: - out = append(out, float64(val)) - case uint: - out = append(out, float64(val)) - case uint64: - out = append(out, float64(val)) - case float32: - out = append(out, float64(val)) - case float64: - out = append(out, float64(val)) - case string: - if val, err := strconv.ParseFloat(val, 64); err == nil { - out = append(out, float64(val)) - } - } - } - return -} diff --git a/util/fncs/args_test.go b/util/fncs/args_test.go deleted file mode 100644 index 474ff00c..00000000 --- a/util/fncs/args_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "testing" - "time" - - "github.com/surrealdb/surrealdb/sql" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestArgs(t *testing.T) { - - now := time.Now() - - args := []interface{}{ - int(1), - int64(1), - uint(1), - uint64(1), - float32(1.5), - float64(1.5), - string("1"), - string("1.5"), - string("test"), - []byte("test"), - map[string]interface{}{"test": true}, - } - - good := args[0:8] - - oops := args[8:11] - - Convey("An argument will convert to string if possible", t, func() { - for _, arg := range args { - val, ok := ensureString(arg) - So(ok, ShouldEqual, true) - So(val, ShouldHaveSameTypeAs, string("")) - } - }) - - Convey("An argument will convert to []byte if possible", t, func() { - for _, arg := range args { - val, ok := ensureBytes(arg) - So(ok, ShouldEqual, true) - So(val, ShouldHaveSameTypeAs, []byte("")) - } - }) - - Convey("An argument will convert to int64 if possible", t, func() { - for _, arg := range good { - val, ok := ensureInt(arg) - So(ok, ShouldEqual, true) - So(val, ShouldHaveSameTypeAs, int64(0)) - } - for _, arg := range oops { - val, ok := ensureInt(arg) - So(ok, ShouldEqual, false) - So(val, ShouldHaveSameTypeAs, int64(0)) - } - }) - - Convey("An argument will convert to float64 if possible", t, func() { - for _, arg := range good { - val, ok := ensureFloat(arg) - So(ok, ShouldEqual, true) - So(val, ShouldHaveSameTypeAs, float64(0)) - } - for _, arg := range oops { - val, ok := ensureFloat(arg) - So(ok, ShouldEqual, false) - So(val, ShouldHaveSameTypeAs, float64(0)) - } - }) - - Convey("An argument will convert to time.Time if possible", t, func() { - res, ok := ensureTime("test") - So(ok, ShouldEqual, false) - So(res, ShouldEqual, time.Unix(0, 0)) - one, ok := ensureTime(now) - So(ok, ShouldEqual, true) - So(one, ShouldEqual, now) - }) - - Convey("An argument will convert to *sql.Point if possible", t, func() { - res, ok := ensurePoint("test") - So(ok, ShouldEqual, false) - So(res, ShouldEqual, nil) - one, ok := ensurePoint(&sql.Point{}) - So(ok, ShouldEqual, true) - So(one, ShouldResemble, &sql.Point{}) - }) - - Convey("An argument will convert to *sql.Circle if possible", t, func() { - res, ok := ensureCircle("test") - So(ok, ShouldEqual, false) - So(res, ShouldEqual, nil) - one, ok := ensureCircle(&sql.Circle{}) - So(ok, ShouldEqual, true) - So(one, ShouldResemble, &sql.Circle{}) - }) - - Convey("An argument will convert to *sql.Polygon if possible", t, func() { - res, ok := ensurePolygon("test") - So(ok, ShouldEqual, false) - So(res, ShouldEqual, nil) - one, ok := ensurePolygon(&sql.Polygon{}) - So(ok, ShouldEqual, true) - So(one, ShouldResemble, &sql.Polygon{}) - }) - - Convey("An argument will convert to *sql.Polygon if possible", t, func() { - res, ok := ensureGeometry("test") - So(ok, ShouldEqual, false) - So(res, ShouldEqual, nil) - one, ok := ensureGeometry(&sql.Point{}) - So(ok, ShouldEqual, true) - So(one, ShouldResemble, &sql.Point{}) - two, ok := ensureGeometry(&sql.Circle{}) - So(ok, ShouldEqual, true) - So(two, ShouldResemble, &sql.Circle{}) - tre, ok := ensureGeometry(&sql.Polygon{}) - So(ok, ShouldEqual, true) - So(tre, ShouldResemble, &sql.Polygon{}) - }) - - Convey("Arguments are converted to []int64 if possible", t, func() { - res := ensureInts(args) - So(res, ShouldHaveSameTypeAs, []int64{}) - So(len(res), ShouldEqual, 8) - }) - - Convey("Arguments are converted to []float64 if possible", t, func() { - res := ensureFloats(args) - So(res, ShouldHaveSameTypeAs, []float64{}) - So(len(res), ShouldEqual, 8) - }) - - Convey("Arguments are converted to []interface{} if possible", t, func() { - for _, arg := range args { - res, _ := ensureSlice(arg) - So(res, ShouldHaveSameTypeAs, []interface{}{}) - } - }) - - Convey("Arguments are converted to map[string]interface{} if possible", t, func() { - for _, arg := range args { - res, _ := ensureObject(arg) - So(res, ShouldHaveSameTypeAs, map[string]interface{}{}) - } - }) - -} diff --git a/util/fncs/array.go b/util/fncs/array.go deleted file mode 100644 index 1b007563..00000000 --- a/util/fncs/array.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" -) - -func array(ctx context.Context, args ...interface{}) (interface{}, error) { - out := make([]interface{}, len(args)) - for i, arg := range args { - out[i] = arg - } - return out, nil -} diff --git a/util/fncs/array_test.go b/util/fncs/array_test.go deleted file mode 100644 index c8eae09d..00000000 --- a/util/fncs/array_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "time" - - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestArray(t *testing.T) { - - var res interface{} - - timer := time.Now() - - Convey("array() works properly", t, func() { - res, _ = Run(context.Background(), "array", 1, 2, 3) - So(res, ShouldResemble, []interface{}{1, 2, 3}) - res, _ = Run(context.Background(), "array", nil, true, "test", timer) - So(res, ShouldResemble, []interface{}{nil, true, "test", timer}) - }) - -} diff --git a/util/fncs/batch.go b/util/fncs/batch.go deleted file mode 100644 index 78eb3451..00000000 --- a/util/fncs/batch.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" -) - -func batch(ctx context.Context, args ...interface{}) (interface{}, error) { - - tb, _ := ensureString(args[0]) - id, _ := ensureSlice(args[1]) - - if len(tb) == 0 { - return nil, txn.ErrorTBNotFound - } - - return sql.NewBatch(tb, id), nil - -} diff --git a/util/fncs/batch_test.go b/util/fncs/batch_test.go deleted file mode 100644 index 78a6b3a5..00000000 --- a/util/fncs/batch_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - "github.com/surrealdb/surrealdb/sql" - . "github.com/smartystreets/goconvey/convey" -) - -func TestBatch(t *testing.T) { - - var res interface{} - - Convey("batch() works properly", t, func() { - res, _ = Run(context.Background(), "batch", 1, []interface{}{1, 2, 3}) - So(res, ShouldResemble, sql.NewBatch("1", []interface{}{1, 2, 3})) - res, _ = Run(context.Background(), "batch", "test", []interface{}{1, 2, 3}) - So(res, ShouldResemble, sql.NewBatch("test", []interface{}{1, 2, 3})) - }) - -} diff --git a/util/fncs/bcrypt.go b/util/fncs/bcrypt.go deleted file mode 100644 index 33ab7215..00000000 --- a/util/fncs/bcrypt.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "golang.org/x/crypto/bcrypt" -) - -func bcryptCompare(ctx context.Context, args ...interface{}) (interface{}, error) { - if h, ok := ensureString(args[0]); ok { - if s, ok := ensureString(args[1]); ok { - e := bcrypt.CompareHashAndPassword([]byte(h), []byte(s)) - if e == nil { - return true, nil - } - } - } - return false, nil -} - -func bcryptGenerate(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p := []byte(s) - o := bcrypt.DefaultCost - return bcrypt.GenerateFromPassword(p, o) -} diff --git a/util/fncs/bcrypt_test.go b/util/fncs/bcrypt_test.go deleted file mode 100644 index 5392df8a..00000000 --- a/util/fncs/bcrypt_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestBcrypt(t *testing.T) { - - Convey("bcrypt.compare(a, b) works properly", t, func() { - res, _ := Run(context.Background(), "bcrypt.compare", "$2y$10$XPMT7nWucHJK113jjomfJ.xa64/jhH7sYrRJ9/0Q2CjzBTGwejUx.", "test") - So(res, ShouldEqual, true) - }) - - Convey("bcrypt.compare(a, b) errors properly", t, func() { - res, _ := Run(context.Background(), "bcrypt.compare", "$2y$10$XPMT7nWucHJK113jjomfJ.xa64/jhH7sYrRJ9/0Q2CjzBTGwejUx.", "wrong") - So(res, ShouldEqual, false) - }) - - Convey("bcrypt.generate(a) works properly", t, func() { - res, _ := Run(context.Background(), "bcrypt.generate", "test") - So(res, ShouldHaveSameTypeAs, []byte("test")) - }) - -} diff --git a/util/fncs/count.go b/util/fncs/count.go deleted file mode 100644 index 032fed78..00000000 --- a/util/fncs/count.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" -) - -func count(ctx context.Context, args ...interface{}) (interface{}, error) { - var out float64 - arr, _ := ensureSlice(args[0]) - for _, v := range arr { - if v != nil { - out++ - } - } - return out, nil -} - -func countIf(ctx context.Context, args ...interface{}) (interface{}, error) { - var out float64 - arr, _ := ensureSlice(args[0]) - for _, v := range arr { - if v == args[1] { - out++ - } - } - return out, nil -} - -func countNot(ctx context.Context, args ...interface{}) (interface{}, error) { - var out float64 - arr, _ := ensureSlice(args[0]) - for _, v := range arr { - if v != args[1] { - out++ - } - } - return out, nil -} diff --git a/util/fncs/count_test.go b/util/fncs/count_test.go deleted file mode 100644 index f93c49cc..00000000 --- a/util/fncs/count_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestCount(t *testing.T) { - - var res interface{} - - var test = []interface{}{int(1), int(2), nil, float64(3.5), float64(4.5), float64(3.5)} - - Convey("count() works properly", t, func() { - res, _ = Run(context.Background(), "count", "test") - So(res, ShouldEqual, 1) - res, _ = Run(context.Background(), "count", 10) - So(res, ShouldEqual, 1) - res, _ = Run(context.Background(), "count", test) - So(res, ShouldEqual, 5) - }) - - Convey("count.if() works properly", t, func() { - res, _ = Run(context.Background(), "count.if", "test", 3.5) - So(res, ShouldEqual, 0) - res, _ = Run(context.Background(), "count.if", 10, 3.5) - So(res, ShouldEqual, 0) - res, _ = Run(context.Background(), "count.if", test, 3.5) - So(res, ShouldEqual, 2) - }) - - Convey("count.not() works properly", t, func() { - res, _ = Run(context.Background(), "count.not", "test", 3.5) - So(res, ShouldEqual, 1) - res, _ = Run(context.Background(), "count.not", 10, 3.5) - So(res, ShouldEqual, 1) - res, _ = Run(context.Background(), "count.not", test, 3.5) - So(res, ShouldEqual, 4) - }) - -} diff --git a/util/fncs/either.go b/util/fncs/either.go deleted file mode 100644 index 90891bdd..00000000 --- a/util/fncs/either.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" -) - -func either(ctx context.Context, args ...interface{}) (interface{}, error) { - for _, a := range args { - switch v := a.(type) { - case nil: - continue - default: - return v, nil - case string: - if v != "" { - return v, nil - } - case int64: - if v != 0 { - return v, nil - } - case float64: - if v != 0 { - return v, nil - } - case []interface{}: - if len(v) != 0 { - return v, nil - } - case map[string]interface{}: - if len(v) != 0 { - return v, nil - } - } - } - return nil, nil -} diff --git a/util/fncs/either_test.go b/util/fncs/either_test.go deleted file mode 100644 index 5f051174..00000000 --- a/util/fncs/either_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestEither(t *testing.T) { - - var res interface{} - - Convey("either() works properly", t, func() { - - res, _ = Run(context.Background(), "either", nil, true) - So(res, ShouldResemble, true) - - res, _ = Run(context.Background(), "either", int64(0), "two") - So(res, ShouldResemble, "two") - res, _ = Run(context.Background(), "either", int64(1), "two") - So(res, ShouldResemble, int64(1)) - res, _ = Run(context.Background(), "either", int64(-1), "two") - So(res, ShouldResemble, int64(-1)) - - res, _ = Run(context.Background(), "either", float64(0), "two") - So(res, ShouldResemble, "two") - res, _ = Run(context.Background(), "either", float64(1), "two") - So(res, ShouldResemble, float64(1)) - res, _ = Run(context.Background(), "either", float64(-1), "two") - So(res, ShouldResemble, float64(-1)) - - res, _ = Run(context.Background(), "either", "", "two") - So(res, ShouldResemble, "two") - res, _ = Run(context.Background(), "either", "one", "two") - So(res, ShouldResemble, "one") - - res, _ = Run(context.Background(), "either", []interface{}{}, []interface{}{"two"}) - So(res, ShouldResemble, []interface{}{"two"}) - res, _ = Run(context.Background(), "either", []interface{}{"one"}, []interface{}{"two"}) - So(res, ShouldResemble, []interface{}{"one"}) - - res, _ = Run(context.Background(), "either", map[string]interface{}{}, map[string]interface{}{"two": true}) - So(res, ShouldResemble, map[string]interface{}{"two": true}) - res, _ = Run(context.Background(), "either", map[string]interface{}{"one": true}, map[string]interface{}{"two": true}) - So(res, ShouldResemble, map[string]interface{}{"one": true}) - - }) - -} diff --git a/util/fncs/email.go b/util/fncs/email.go deleted file mode 100644 index c56a88bd..00000000 --- a/util/fncs/email.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "strings" -) - -func emailUser(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - if p := strings.LastIndexByte(v, '@'); p > 0 { - return v[:p], nil - } - return nil, nil -} - -func emailDomain(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - if p := strings.LastIndexByte(v, '@'); p > 0 { - return v[p+1:], nil - } - return nil, nil -} diff --git a/util/fncs/email_test.go b/util/fncs/email_test.go deleted file mode 100644 index e958a37b..00000000 --- a/util/fncs/email_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestEmail(t *testing.T) { - - Convey("email.user(a) works properly", t, func() { - res, _ := Run(context.Background(), "email.user", "tobie@abcum.com") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "tobie") - }) - - Convey("email.user(a) errors properly", t, func() { - res, _ := Run(context.Background(), "email.user", "test") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("email.domain(a) works properly", t, func() { - res, _ := Run(context.Background(), "email.domain", "tobie@abcum.com") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "abcum.com") - }) - - Convey("email.domain(a) errors properly", t, func() { - res, _ := Run(context.Background(), "email.domain", "test") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - -} diff --git a/util/fncs/fnc.go b/util/fncs/fnc.go deleted file mode 100644 index db656be6..00000000 --- a/util/fncs/fnc.go +++ /dev/null @@ -1,385 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import "context" - -func Run(ctx context.Context, name string, args ...interface{}) (interface{}, error) { - - switch name { - - case "array": - return array(ctx, args...) - case "batch": - return batch(ctx, args...) - case "difference": - return difference(ctx, args...) - case "distinct": - return distinct(ctx, args...) - case "either": - return either(ctx, args...) - case "get": - return get(ctx, args...) - case "if": - return ifel(ctx, args...) - case "intersect": - return intersect(ctx, args...) - case "model": - return model(ctx, args...) - case "regex": - return regex(ctx, args...) - case "table": - return table(ctx, args...) - case "thing": - return thing(ctx, args...) - case "union": - return union(ctx, args...) - - // Count implementation - case "count": - return count(ctx, args...) - case "count.if": - return countIf(ctx, args...) - case "count.not": - return countNot(ctx, args...) - - // Purge implementation - case "purge": - return purge(ctx, args...) - case "purge.if": - return purgeIf(ctx, args...) - case "purge.not": - return purgeNot(ctx, args...) - - // Geo implementation - case "geo.point": - return geoPoint(ctx, args...) - case "geo.circle": - return geoCircle(ctx, args...) - case "geo.polygon": - return geoPolygon(ctx, args...) - case "geo.contains": - return geoContains(ctx, args...) - case "geo.distance": - return geoDistance(ctx, args...) - case "geo.inside": - return geoInside(ctx, args...) - case "geo.intersects": - return geoIntersects(ctx, args...) - case "geo.hash.decode": - return geoHashDecode(ctx, args...) - case "geo.hash.encode": - return geoHashEncode(ctx, args...) - - // Http implementation - case "http.head": - return httpHead(ctx, args...) - case "http.get": - return httpGet(ctx, args...) - case "http.put": - return httpPut(ctx, args...) - case "http.post": - return httpPost(ctx, args...) - case "http.patch": - return httpPatch(ctx, args...) - case "http.delete": - return httpDelete(ctx, args...) - case "http.async.head": - return httpAsyncHead(ctx, args...) - case "http.async.get": - return httpAsyncGet(ctx, args...) - case "http.async.put": - return httpAsyncPut(ctx, args...) - case "http.async.post": - return httpAsyncPost(ctx, args...) - case "http.async.patch": - return httpAsyncPatch(ctx, args...) - case "http.async.delete": - return httpAsyncDelete(ctx, args...) - - // Math implementation - case "math.abs": - return mathAbs(ctx, args...) - case "math.bottom": - return mathBottom(ctx, args...) - case "math.ceil": - return mathCeil(ctx, args...) - case "math.correlation": - return mathCorrelation(ctx, args...) - case "math.covariance": - return mathCovariance(ctx, args...) - case "math.fixed": - return mathFixed(ctx, args...) - case "math.floor": - return mathFloor(ctx, args...) - case "math.geometricmean": - return mathGeometricmean(ctx, args...) - case "math.harmonicmean": - return mathHarmonicmean(ctx, args...) - case "math.interquartile": - return mathInterquartile(ctx, args...) - case "math.max": - return mathMax(ctx, args...) - case "math.mean": - return mathMean(ctx, args...) - case "math.median": - return mathMedian(ctx, args...) - case "math.midhinge": - return mathMidhinge(ctx, args...) - case "math.min": - return mathMin(ctx, args...) - case "math.mode": - return mathMode(ctx, args...) - case "math.nearestrank": - return mathNearestRank(ctx, args...) - case "math.percentile": - return mathPercentile(ctx, args...) - case "math.round": - return mathRound(ctx, args...) - case "math.sample": - return mathSample(ctx, args...) - case "math.spread": - return mathSpread(ctx, args...) - case "math.sqrt": - return mathSqrt(ctx, args...) - case "math.stddev": - return mathStddev(ctx, args...) - case "math.sum": - return mathSum(ctx, args...) - case "math.top": - return mathTop(ctx, args...) - case "math.trimean": - return mathTrimean(ctx, args...) - case "math.variance": - return mathVariance(ctx, args...) - - // String implementation - case "string.concat": - return stringConcat(ctx, args...) - case "string.contains": - return stringContains(ctx, args...) - case "string.endsWith": - return stringEndsWith(ctx, args...) - case "string.format": - return stringFormat(ctx, args...) - case "string.includes": - return stringIncludes(ctx, args...) - case "string.join": - return stringJoin(ctx, args...) - case "string.length": - return stringLength(ctx, args...) - case "string.levenshtein": - return stringLevenshtein(ctx, args...) - case "string.lowercase": - return stringLowercase(ctx, args...) - case "string.repeat": - return stringRepeat(ctx, args...) - case "string.replace": - return stringReplace(ctx, args...) - case "string.reverse": - return stringReverse(ctx, args...) - case "string.search": - return stringSearch(ctx, args...) - case "string.slice": - return stringSlice(ctx, args...) - case "string.slug": - return stringSlug(ctx, args...) - case "string.split": - return stringSplit(ctx, args...) - case "string.startsWith": - return stringStartsWith(ctx, args...) - case "string.substr": - return stringSubstr(ctx, args...) - case "string.trim": - return stringTrim(ctx, args...) - case "string.uppercase": - return stringUppercase(ctx, args...) - case "string.words": - return stringWords(ctx, args...) - - // Hash implementation - case "hash.md5": - return hashMd5(ctx, args...) - case "hash.sha1": - return hashSha1(ctx, args...) - case "hash.sha256": - return hashSha256(ctx, args...) - case "hash.sha512": - return hashSha512(ctx, args...) - - // Time implementation - case "time.now": - return timeNow(ctx, args...) - case "time.add": - return timeAdd(ctx, args...) - case "time.age": - return timeAge(ctx, args...) - case "time.floor": - return timeFloor(ctx, args...) - case "time.round": - return timeRound(ctx, args...) - case "time.day": - return timeDay(ctx, args...) - case "time.hour": - return timeHour(ctx, args...) - case "time.mins": - return timeMins(ctx, args...) - case "time.month": - return timeMonth(ctx, args...) - case "time.nano": - return timeNano(ctx, args...) - case "time.secs": - return timeSecs(ctx, args...) - case "time.unix": - return timeUnix(ctx, args...) - case "time.wday": - return timeWday(ctx, args...) - case "time.week": - return timeWeek(ctx, args...) - case "time.yday": - return timeYday(ctx, args...) - case "time.year": - return timeYear(ctx, args...) - - // Url implementation - case "url.domain": - return urlHost(ctx, args...) - case "url.host": - return urlHost(ctx, args...) - case "url.port": - return urlPort(ctx, args...) - case "url.path": - return urlPath(ctx, args...) - - // Email implementation - case "email.user": - return emailUser(ctx, args...) - case "email.domain": - return emailDomain(ctx, args...) - - // Bcrypt implementation - case "bcrypt.compare": - return bcryptCompare(ctx, args...) - case "bcrypt.generate": - return bcryptGenerate(ctx, args...) - - // Scrypt implementation - case "scrypt.compare": - return scryptCompare(ctx, args...) - case "scrypt.generate": - return scryptGenerate(ctx, args...) - - // Check implementation - case "is.alpha": - return isAlpha(ctx, args...) - case "is.alphanum": - return isAlphanum(ctx, args...) - case "is.ascii": - return isAscii(ctx, args...) - case "is.domain": - return isDomain(ctx, args...) - case "is.email": - return isEmail(ctx, args...) - case "is.hexadecimal": - return isHexadecimal(ctx, args...) - case "is.latitude": - return isLatitude(ctx, args...) - case "is.longitude": - return isLongitude(ctx, args...) - case "is.numeric": - return isNumeric(ctx, args...) - case "is.semver": - return isSemver(ctx, args...) - case "is.uuid": - return isUuid(ctx, args...) - - // Rand implementation - case "rand": - return rand(ctx, args...) - case "guid": - return randGuid(ctx, args...) - case "uuid": - return randUuid(ctx, args...) - case "rand.bool": - return randBool(ctx, args...) - case "rand.guid": - return randGuid(ctx, args...) - case "rand.uuid": - return randUuid(ctx, args...) - case "rand.enum": - return randEnum(ctx, args...) - case "rand.time": - return randTime(ctx, args...) - case "rand.string": - return randString(ctx, args...) - case "rand.integer": - return randInteger(ctx, args...) - case "rand.decimal": - return randDecimal(ctx, args...) - case "rand.word": - return randWord(ctx, args...) - case "rand.sentence": - return randSentence(ctx, args...) - case "rand.paragraph": - return randParagraph(ctx, args...) - case "rand.person.email": - return randPersonEmail(ctx, args...) - case "rand.person.phone": - return randPersonPhone(ctx, args...) - case "rand.person.fullname": - return randPersonFullname(ctx, args...) - case "rand.person.firstname": - return randPersonFirstname(ctx, args...) - case "rand.person.lastname": - return randPersonLastname(ctx, args...) - case "rand.person.username": - return randPersonUsername(ctx, args...) - case "rand.person.jobtitle": - return randPersonJobtitle(ctx, args...) - case "rand.company.name": - return randCompanyName(ctx, args...) - case "rand.company.industry": - return randCompanyIndustry(ctx, args...) - case "rand.location.name": - return randLocationName(ctx, args...) - case "rand.location.address": - return randLocationAddress(ctx, args...) - case "rand.location.street": - return randLocationStreet(ctx, args...) - case "rand.location.city": - return randLocationCity(ctx, args...) - case "rand.location.state": - return randLocationState(ctx, args...) - case "rand.location.county": - return randLocationCounty(ctx, args...) - case "rand.location.zipcode": - return randLocationZipcode(ctx, args...) - case "rand.location.postcode": - return randLocationPostcode(ctx, args...) - case "rand.location.country": - return randLocationCountry(ctx, args...) - case "rand.location.altitude": - return randLocationAltitude(ctx, args...) - case "rand.location.latitude": - return randLocationLatitude(ctx, args...) - case "rand.location.longitude": - return randLocationLongitude(ctx, args...) - - default: - return nil, nil // Should never get here - - } - -} diff --git a/util/fncs/fnc_test.go b/util/fncs/fnc_test.go deleted file mode 100644 index 0e91a0aa..00000000 --- a/util/fncs/fnc_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestNil(t *testing.T) { - - Convey("invalid.function() returns nil", t, func() { - res, _ := Run(context.Background(), "invalid.function") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - -} diff --git a/util/fncs/geo.go b/util/fncs/geo.go deleted file mode 100644 index dfe23ac1..00000000 --- a/util/fncs/geo.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/geof" -) - -func geoPoint(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 1: - if p, ok := ensurePoint(args[0]); ok { - return p, nil - } - if p := ensureFloats(args[0]); len(p) == 2 { - return sql.NewPoint(p[0], p[1]), nil - } - case 2: - if lng, ok := ensureFloat(args[0]); ok { - if lat, ok := ensureFloat(args[1]); ok { - return sql.NewPoint(lng, lat), nil - } - } - } - return nil, nil -} - -func geoCircle(ctx context.Context, args ...interface{}) (interface{}, error) { - if cen, ok := ensurePoint(args[0]); ok { - if rad, ok := ensureFloat(args[1]); ok { - return sql.NewCircle(cen, rad), nil - } - } - if val := ensureFloats(args[0]); len(val) == 2 { - cen := sql.NewPoint(val[0], val[1]) - if rad, ok := ensureFloat(args[1]); ok { - return sql.NewCircle(cen, rad), nil - } - } - return nil, nil -} - -func geoPolygon(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0, 2: - // Not enough arguments, so just ignore - case 1: - var pnts []*sql.Point - if a, ok := ensureSlice(args[0]); ok { - for _, a := range a { - if p, _ := ensurePoint(a); p != nil { - pnts = append(pnts, p) - } else if p := ensureFloats(a); len(p) == 2 { - pnts = append(pnts, sql.NewPoint(p[0], p[1])) - } else { - return nil, nil - } - } - return sql.NewPolygon(pnts...), nil - } - default: - var pnts []*sql.Point - for _, a := range args { - if p, _ := ensurePoint(a); p != nil { - pnts = append(pnts, p) - } else if p := ensureFloats(a); len(p) == 2 { - pnts = append(pnts, sql.NewPoint(p[0], p[1])) - } else { - return nil, nil - } - } - return sql.NewPolygon(pnts...), nil - } - return nil, nil -} - -func geoContains(ctx context.Context, args ...interface{}) (interface{}, error) { - if a, ok := ensurePolygon(args[0]); ok { - if b, ok := ensurePoint(args[1]); ok { - return geof.Contains(a, b), nil - } - } - return false, nil -} - -func geoDistance(ctx context.Context, args ...interface{}) (interface{}, error) { - if pnt, ok := ensurePoint(args[0]); ok { - if frm, ok := ensurePoint(args[1]); ok { - return geof.Haversine(pnt, frm), nil - } - } - return -1, nil -} - -func geoInside(ctx context.Context, args ...interface{}) (interface{}, error) { - if a, ok := ensurePoint(args[0]); ok { - if b, ok := ensurePolygon(args[1]); ok { - return geof.Inside(a, b), nil - } - } - return false, nil -} - -func geoIntersects(ctx context.Context, args ...interface{}) (interface{}, error) { - if a, ok := ensureGeometry(args[0]); ok { - if b, ok := ensureGeometry(args[1]); ok { - return geof.Intersects(a, b), nil - } - } - return false, nil -} - -func geoHashDecode(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - return geof.GeohashDecode(s), nil -} - -func geoHashEncode(ctx context.Context, args ...interface{}) (interface{}, error) { - if pnt, ok := ensurePoint(args[0]); ok { - if acc, ok := ensureInt(args[1]); ok { - return geof.GeohashEncode(pnt, acc), nil - } - } - return nil, nil -} diff --git a/util/fncs/geo_test.go b/util/fncs/geo_test.go deleted file mode 100644 index a7a8f9ef..00000000 --- a/util/fncs/geo_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - "github.com/surrealdb/surrealdb/sql" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestGeo(t *testing.T) { - - var res interface{} - - Convey("geo.point(a, b) works properly", t, func() { - res, _ = Run(context.Background(), "geo.point", "test", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "geo.point", &sql.Point{-77.037852, 38.898556}) - So(res, ShouldResemble, &sql.Point{-77.037852, 38.898556}) - res, _ = Run(context.Background(), "geo.point", []interface{}{-77.037852, 38.898556}) - So(res, ShouldResemble, &sql.Point{-77.037852, 38.898556}) - res, _ = Run(context.Background(), "geo.point", -77.037852, 38.898556) - So(res, ShouldResemble, &sql.Point{-77.037852, 38.898556}) - }) - - Convey("geo.circle(a, b) works properly", t, func() { - res, _ = Run(context.Background(), "geo.circle", "test", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "geo.circle", &sql.Point{-77.037852, 38.898556}, 100) - So(res, ShouldResemble, &sql.Circle{&sql.Point{-77.037852, 38.898556}, 100}) - res, _ = Run(context.Background(), "geo.circle", []interface{}{-77.037852, 38.898556}, 100) - So(res, ShouldResemble, &sql.Circle{&sql.Point{-77.037852, 38.898556}, 100}) - }) - - Convey("geo.polygon(a, b) works properly", t, func() { - res, _ = Run(context.Background(), "geo.polygon", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "geo.polygon", "test", "test", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "geo.polygon", "test", &sql.Point{}, &sql.Point{}, &sql.Point{}) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "geo.polygon", &sql.Point{}, &sql.Point{}, &sql.Point{}, &sql.Point{}) - So(res, ShouldResemble, &sql.Polygon{sql.Points{&sql.Point{}, &sql.Point{}, &sql.Point{}, &sql.Point{}}}) - }) - - Convey("geo.distance(a, b, c, d) works properly", t, func() { - res, _ = Run(context.Background(), "geo.distance", &sql.Point{-77.037852, 38.898556}, &sql.Point{-77.043934, 38.897147}) - So(res, ShouldEqual, 549.1557912042738) - }) - - Convey("geo.distance(a, b, c, d) errors properly", t, func() { - res, _ = Run(context.Background(), "geo.distance", &sql.Point{-77.037852, 38.898556}, "null") - So(res, ShouldEqual, -1) - }) - - Convey("geo.hash.decode(a) works properly", t, func() { - res, _ = Run(context.Background(), "geo.hash.decode", "dqcjq") - So(res, ShouldResemble, &sql.Point{38.91357421875, -77.05810546875}) - res, _ = Run(context.Background(), "geo.hash.decode", "dqcjqcq8x") - So(res, ShouldResemble, &sql.Point{38.9230709412368, -77.06750950572314}) - }) - - Convey("geo.hash.encode(a, b, c) works properly", t, func() { - res, _ = Run(context.Background(), "geo.hash.encode", &sql.Point{-77.037852, 38.898556}, 5) - So(res, ShouldEqual, "dqcjq") - res, _ = Run(context.Background(), "geo.hash.encode", &sql.Point{-77.037852, 38.898556}, 9) - So(res, ShouldEqual, "dqcjqcq8x") - }) - - Convey("geo.hash.encode(a, b, c) errors properly", t, func() { - res, _ = Run(context.Background(), "geo.hash.encode", 0, 0, "null") - So(res, ShouldEqual, nil) - }) - -} diff --git a/util/fncs/get.go b/util/fncs/get.go deleted file mode 100644 index daa047db..00000000 --- a/util/fncs/get.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func get(ctx context.Context, args ...interface{}) (interface{}, error) { - doc := data.Consume(args[0]) - switch fld := args[1].(type) { - case string: - return doc.Get(fld).Data(), nil - case *sql.Value: - return doc.Get(fld.VA).Data(), nil - } - return nil, nil -} diff --git a/util/fncs/get_test.go b/util/fncs/get_test.go deleted file mode 100644 index 4de87f4f..00000000 --- a/util/fncs/get_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - "github.com/surrealdb/surrealdb/sql" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestGet(t *testing.T) { - - var res interface{} - - var doc = map[string]interface{}{ - "object": map[string]interface{}{ - "test": "ok", - }, - "string": "test", - "bool": true, - "int": 13, - } - - Convey("get(a, b) works properly", t, func() { - res, _ = Run(context.Background(), "get", doc, &sql.Value{"object.test"}) - So(res, ShouldEqual, "ok") - res, _ = Run(context.Background(), "get", doc, "object.test") - So(res, ShouldEqual, "ok") - res, _ = Run(context.Background(), "get", doc, "string") - So(res, ShouldEqual, "test") - res, _ = Run(context.Background(), "get", doc, "bool") - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "get", doc, "int") - So(res, ShouldEqual, 13) - res, _ = Run(context.Background(), "get", doc, "err") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "get", doc, nil) - So(res, ShouldEqual, nil) - }) - -} diff --git a/util/fncs/hash.go b/util/fncs/hash.go deleted file mode 100644 index 43ed2160..00000000 --- a/util/fncs/hash.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/hex" -) - -func hashMd5(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - h := md5.New() - h.Write([]byte(v)) - s := h.Sum(nil) - return hex.EncodeToString(s), nil -} - -func hashSha1(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - h := sha1.New() - h.Write([]byte(v)) - s := h.Sum(nil) - return hex.EncodeToString(s), nil -} - -func hashSha256(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - h := sha256.New() - h.Write([]byte(v)) - s := h.Sum(nil) - return hex.EncodeToString(s), nil -} - -func hashSha512(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - h := sha512.New() - h.Write([]byte(v)) - s := h.Sum(nil) - return hex.EncodeToString(s), nil -} diff --git a/util/fncs/hash_test.go b/util/fncs/hash_test.go deleted file mode 100644 index cc0c36ef..00000000 --- a/util/fncs/hash_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestHash(t *testing.T) { - - Convey("hash.md5(a) works properly", t, func() { - res, _ := Run(context.Background(), "hash.md5", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "098f6bcd4621d373cade4e832627b4f6") - }) - - Convey("hash.sha1(a) works properly", t, func() { - res, _ := Run(context.Background(), "hash.sha1", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3") - }) - - Convey("hash.sha256(a) works properly", t, func() { - res, _ := Run(context.Background(), "hash.sha256", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08") - }) - - Convey("hash.sha512(a) works properly", t, func() { - res, _ := Run(context.Background(), "hash.sha512", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff") - }) - -} diff --git a/util/fncs/http.go b/util/fncs/http.go deleted file mode 100644 index daa8f2a3..00000000 --- a/util/fncs/http.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "bytes" - "context" - "errors" - "io" - "io/ioutil" - "net/http" - "time" - - "encoding/json" - - "golang.org/x/net/context/ctxhttp" - - "github.com/surrealdb/surrealdb/util/build" - "github.com/surrealdb/surrealdb/util/hook" -) - -type opts map[string]interface{} - -var version = build.GetInfo().Ver - -var httpResponseError = errors.New("HTTP response error") - -func httpHead(ctx context.Context, args ...interface{}) (interface{}, error) { - return runSync(ctx, "HEAD", args...) -} - -func httpGet(ctx context.Context, args ...interface{}) (interface{}, error) { - return runSync(ctx, "GET", args...) -} - -func httpPut(ctx context.Context, args ...interface{}) (interface{}, error) { - return runSync(ctx, "PUT", args...) -} - -func httpPost(ctx context.Context, args ...interface{}) (interface{}, error) { - return runSync(ctx, "POST", args...) -} - -func httpPatch(ctx context.Context, args ...interface{}) (interface{}, error) { - return runSync(ctx, "PATCH", args...) -} - -func httpDelete(ctx context.Context, args ...interface{}) (interface{}, error) { - return runSync(ctx, "DELETE", args...) -} - -func httpAsyncHead(ctx context.Context, args ...interface{}) (interface{}, error) { - return runAsync(ctx, "HEAD", args...) -} - -func httpAsyncGet(ctx context.Context, args ...interface{}) (interface{}, error) { - return runAsync(ctx, "GET", args...) -} - -func httpAsyncPut(ctx context.Context, args ...interface{}) (interface{}, error) { - return runAsync(ctx, "PUT", args...) -} - -func httpAsyncPost(ctx context.Context, args ...interface{}) (interface{}, error) { - return runAsync(ctx, "POST", args...) -} - -func httpAsyncPatch(ctx context.Context, args ...interface{}) (interface{}, error) { - return runAsync(ctx, "PATCH", args...) -} - -func httpAsyncDelete(ctx context.Context, args ...interface{}) (interface{}, error) { - return runAsync(ctx, "DELETE", args...) -} - -func runSync(ctx context.Context, met string, args ...interface{}) (interface{}, error) { - url, bdy, opt := httpCnf(met, args...) - out, _ := httpRes(ctx, met, url, bdy, opt) - return out, nil -} - -func runAsync(ctx context.Context, met string, args ...interface{}) (interface{}, error) { - url, bdy, opt := httpCnf(met, args...) - ctx = context.Background() - go hook.NewBackoff(5, 5, 10*time.Second).Run(ctx, func() error { - return httpErr(httpReq(ctx, met, url, bdy, opt)) - }) - return nil, nil -} - -func httpCnf(met string, args ...interface{}) (url string, bdy io.Reader, opt opts) { - var bit []byte - switch met { - case "HEAD", "GET", "DELETE": - switch len(args) { - case 1: - url, _ = ensureString(args[0]) - case 2: - url, _ = ensureString(args[0]) - opt, _ = ensureObject(args[1]) - } - case "PUT", "POST", "PATCH": - switch len(args) { - case 1: - url, _ = ensureString(args[0]) - case 2: - url, _ = ensureString(args[0]) - switch v := args[1].(type) { - case []interface{}, map[string]interface{}: - bit, _ = json.Marshal(v) - default: - bit, _ = ensureBytes(v) - } - case 3: - url, _ = ensureString(args[0]) - switch v := args[1].(type) { - case []interface{}, map[string]interface{}: - bit, _ = json.Marshal(v) - default: - bit, _ = ensureBytes(v) - } - opt, _ = ensureObject(args[2]) - } - } - return url, bytes.NewReader(bit), opt -} - -func httpReq(ctx context.Context, met, url string, body io.Reader, conf opts) (*http.Response, error) { - - cli := new(http.Client) - - req, err := http.NewRequest(met, url, body) - if err != nil { - return nil, err - } - - req.Header.Set("User-Agent", "SurrealDB HTTP/"+version) - - if val, ok := conf["auth"]; ok { - if opt, ok := ensureObject(val); ok { - user, _ := ensureString(opt["user"]) - pass, _ := ensureString(opt["pass"]) - req.SetBasicAuth(user, pass) - } - } - - if val, ok := conf["head"]; ok { - if opt, ok := ensureObject(val); ok { - for key, v := range opt { - head, _ := ensureString(v) - req.Header.Set(key, head) - } - } - } - - res, err := ctxhttp.Do(ctx, cli, req) - if err != nil { - return nil, err - } - - return res, nil - -} - -func httpRes(ctx context.Context, met, url string, body io.Reader, conf opts) (interface{}, error) { - - var out interface{} - - res, err := httpReq(ctx, met, url, body, conf) - if err != nil { - return nil, err - } - - bdy, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - - err = json.Unmarshal(bdy, &out) - if err != nil { - if len(bdy) != 0 { - return bdy, nil - } - } - - return out, nil - -} - -func httpErr(res *http.Response, err error) error { - if err != nil { - return err - } - if res.StatusCode >= 500 { - return httpResponseError - } - return nil -} diff --git a/util/fncs/http_test.go b/util/fncs/http_test.go deleted file mode 100644 index 32a2398b..00000000 --- a/util/fncs/http_test.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "fmt" - "io" - "net/http" - "net/http/httptest" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestHttp(t *testing.T) { - - var res interface{} - var jsn = `{"test":true, "temp":"text"}` - var obj = map[string]interface{}{"temp": "text", "test": true} - var txt = `` - var opt = map[string]interface{}{ - "auth": map[string]interface{}{"user": "u", "pass": "p"}, - "head": map[string]interface{}{"x-test": true}, - } - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "HEAD", "DELETE": - // Return nothing - case "GET": - fmt.Fprint(w, txt) - case "PUT", "POST", "PATCH": - io.Copy(w, r.Body) - } - })) - - defer srv.Close() - - Convey("http.head(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.head", srv.URL) - So(res, ShouldResemble, nil) - }) - - Convey("http.get(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.get", srv.URL) - So(res, ShouldResemble, []byte(txt)) - res, _ = Run(context.Background(), "http.get", srv.URL, opt) - So(res, ShouldResemble, []byte(txt)) - }) - - Convey("http.put(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.put", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.put", srv.URL, txt) - So(res, ShouldResemble, []byte(txt)) - res, _ = Run(context.Background(), "http.put", srv.URL, jsn) - So(res, ShouldResemble, obj) - res, _ = Run(context.Background(), "http.put", srv.URL, jsn, opt) - So(res, ShouldResemble, obj) - }) - - Convey("http.post(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.post", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.post", srv.URL, txt) - So(res, ShouldResemble, []byte(txt)) - res, _ = Run(context.Background(), "http.post", srv.URL, jsn) - So(res, ShouldResemble, obj) - res, _ = Run(context.Background(), "http.post", srv.URL, jsn, opt) - So(res, ShouldResemble, obj) - }) - - Convey("http.patch(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.patch", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.patch", srv.URL, txt) - So(res, ShouldResemble, []byte(txt)) - res, _ = Run(context.Background(), "http.patch", srv.URL, jsn) - So(res, ShouldResemble, obj) - res, _ = Run(context.Background(), "http.patch", srv.URL, jsn, opt) - So(res, ShouldResemble, obj) - }) - - Convey("http.delete(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.delete", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.delete", srv.URL, opt) - So(res, ShouldResemble, nil) - }) - - Convey("http.async.head(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.async.head", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.head", srv.URL, opt) - So(res, ShouldResemble, nil) - }) - - Convey("http.async.get(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.async.get", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.get", srv.URL, opt) - So(res, ShouldResemble, nil) - }) - - Convey("http.async.put(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.async.put", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.put", srv.URL, txt) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.put", srv.URL, jsn) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.put", srv.URL, jsn, opt) - So(res, ShouldResemble, nil) - }) - - Convey("http.async.post(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.async.post", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.post", srv.URL, txt) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.post", srv.URL, jsn) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.post", srv.URL, jsn, opt) - So(res, ShouldResemble, nil) - }) - - Convey("http.async.patch(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.async.patch", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.patch", srv.URL, txt) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.patch", srv.URL, jsn) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.patch", srv.URL, jsn, opt) - So(res, ShouldResemble, nil) - }) - - Convey("http.async.delete(a) works properly", t, func() { - res, _ = Run(context.Background(), "http.async.delete", srv.URL) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "http.async.delete", srv.URL, opt) - So(res, ShouldResemble, nil) - }) - -} diff --git a/util/fncs/if.go b/util/fncs/if.go deleted file mode 100644 index eb4269d6..00000000 --- a/util/fncs/if.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" -) - -func ifel(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureBool(args[0]); ok && val { - return args[1], nil - } - return args[2], nil -} diff --git a/util/fncs/if_test.go b/util/fncs/if_test.go deleted file mode 100644 index ead9f0bb..00000000 --- a/util/fncs/if_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestIf(t *testing.T) { - - var res interface{} - - Convey("if(a, b, c) works properly", t, func() { - res, _ = Run(context.Background(), "if", true, "yes", "no") - So(res, ShouldEqual, "yes") - res, _ = Run(context.Background(), "if", "true", "yes", "no") - So(res, ShouldEqual, "yes") - res, _ = Run(context.Background(), "if", false, "yes", "no") - So(res, ShouldEqual, "no") - res, _ = Run(context.Background(), "if", "false", "yes", "no") - So(res, ShouldEqual, "no") - res, _ = Run(context.Background(), "if", "something", "yes", "no") - So(res, ShouldEqual, "no") - }) - -} diff --git a/util/fncs/is.go b/util/fncs/is.go deleted file mode 100644 index 11200fad..00000000 --- a/util/fncs/is.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "net/mail" - "regexp" -) - -const ( - sAlpha string = "^[a-zA-Z]+$" - sAlphanum string = "^[a-zA-Z0-9]+$" - sAscii string = "^[\x00-\x7F]+$" - sDomain string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` - sHexadecimal string = "^[0-9a-fA-F]+$" - sLatitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" - sLongitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - sNumeric string = "^[0-9]+$" - sSemver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$" - sUUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" -) - -var ( - rAlpha = regexp.MustCompile(sAlpha) - rAlphanum = regexp.MustCompile(sAlphanum) - rAscii = regexp.MustCompile(sAscii) - rDomain = regexp.MustCompile(sDomain) - rHexadecimal = regexp.MustCompile(sHexadecimal) - rLatitude = regexp.MustCompile(sLatitude) - rLongitude = regexp.MustCompile(sLongitude) - rNumeric = regexp.MustCompile(sNumeric) - rSemver = regexp.MustCompile(sSemver) - rUUID = regexp.MustCompile(sUUID) -) - -func isAlpha(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rAlpha.MatchString(val), nil - } - return false, nil -} - -func isAlphanum(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rAlphanum.MatchString(val), nil - } - return false, nil -} - -func isAscii(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rAscii.MatchString(val), nil - } - return false, nil -} - -func isDomain(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rDomain.MatchString(val), nil - } - return false, nil -} - -func isEmail(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); len(val) > 0 && ok { - pse, err := mail.ParseAddress(val) - return err == nil && val == pse.Address, nil - } - return false, nil -} - -func isHexadecimal(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rHexadecimal.MatchString(val), nil - } - return false, nil -} - -func isLatitude(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rLatitude.MatchString(val), nil - } - return false, nil -} - -func isLongitude(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rLongitude.MatchString(val), nil - } - return false, nil -} - -func isNumeric(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rNumeric.MatchString(val), nil - } - return false, nil -} - -func isSemver(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rSemver.MatchString(val), nil - } - return false, nil -} - -func isUuid(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureString(args[0]); ok { - return rUUID.MatchString(val), nil - } - return false, nil -} diff --git a/util/fncs/is_test.go b/util/fncs/is_test.go deleted file mode 100644 index cc28f2da..00000000 --- a/util/fncs/is_test.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestIs(t *testing.T) { - - var res interface{} - - Convey("is.alpha(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.alpha", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.alpha", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.alpha", "aBcDe") - So(res, ShouldEqual, true) - }) - - Convey("is.alphanum(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.alphanum", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.alphanum", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.alphanum", "aB3De") - So(res, ShouldEqual, true) - }) - - Convey("is.ascii(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.ascii", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.ascii", "testing®") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.ascii", "aB3De") - So(res, ShouldEqual, true) - }) - - Convey("is.domain(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.domain", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.domain", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.domain", "abcum.com") - So(res, ShouldEqual, true) - }) - - Convey("is.email(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.email", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.email", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.email", "info@abcum.com") - So(res, ShouldEqual, true) - }) - - Convey("is.hexadecimal(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.hexadecimal", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.hexadecimal", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.hexadecimal", "00bfff") - So(res, ShouldEqual, true) - }) - - Convey("is.latitude(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.latitude", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.latitude", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.latitude", 0) - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.latitude", -90) - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.latitude", +90) - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.latitude", "-90") - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.latitude", "+90") - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.latitude", -95) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.latitude", +95) - So(res, ShouldEqual, false) - }) - - Convey("is.longitude(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.longitude", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.longitude", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.longitude", 0) - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.longitude", -180) - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.longitude", +180) - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.longitude", "-180") - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.longitude", "+180") - So(res, ShouldEqual, true) - res, _ = Run(context.Background(), "is.longitude", -185) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.longitude", +185) - So(res, ShouldEqual, false) - }) - - Convey("is.numeric(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.numeric", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.numeric", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.numeric", "123456") - So(res, ShouldEqual, true) - }) - - Convey("is.semver(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.semver", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.semver", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.semver", "1.0.32") - So(res, ShouldEqual, true) - }) - - Convey("is.uuid(a) works properly", t, func() { - res, _ = Run(context.Background(), "is.uuid", nil) - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.uuid", "test-©") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "is.uuid", "8ddb11e8-755f-47cf-a84f-8033d1cfa1b9") - So(res, ShouldEqual, true) - }) - -} diff --git a/util/fncs/math.go b/util/fncs/math.go deleted file mode 100644 index e95a7df7..00000000 --- a/util/fncs/math.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/util/math" -) - -func mathAbs(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureFloat(args[0]); ok { - return outputFloat(math.Abs(val)) - } - return nil, nil -} - -func mathBottom(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - if take, ok := ensureInt(args[1]); ok { - return math.Bottom(vals, int(take)), nil - } - return nil, nil -} - -func mathCeil(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureFloat(args[0]); ok { - return outputFloat(math.Ceil(val)) - } - return nil, nil -} - -func mathCorrelation(ctx context.Context, args ...interface{}) (interface{}, error) { - a := ensureFloats(args[0]) - b := ensureFloats(args[1]) - return outputFloat(math.Correlation(a, b)) -} - -func mathCovariance(ctx context.Context, args ...interface{}) (interface{}, error) { - a := ensureFloats(args[0]) - b := ensureFloats(args[1]) - return outputFloat(math.Covariance(a, b)) -} - -func mathFixed(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureFloat(args[0]); ok { - if pre, ok := ensureInt(args[1]); ok { - return outputFixed(val, pre) - } - } - return nil, nil -} - -func mathFloor(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureFloat(args[0]); ok { - return outputFloat(math.Floor(val)) - } - return nil, nil -} - -func mathGeometricmean(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.GeometricMean(vals)) -} - -func mathHarmonicmean(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.HarmonicMean(vals)) -} - -func mathInterquartile(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.InterQuartileRange(vals)) -} - -func mathMax(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Max(vals)) -} - -func mathMean(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Mean(vals)) -} - -func mathMedian(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Median(vals)) -} - -func mathMidhinge(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Midhinge(vals)) -} - -func mathMin(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Min(vals)) -} - -func mathMode(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return math.Mode(vals), nil -} - -func mathNearestRank(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - if perc, ok := ensureFloat(args[1]); ok { - return outputFloat(math.NearestRankPercentile(vals, perc)) - } - return nil, nil -} - -func mathPercentile(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - if perc, ok := ensureFloat(args[1]); ok { - return outputFloat(math.Percentile(vals, perc)) - } - return nil, nil -} - -func mathRound(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureFloat(args[0]); ok { - return outputFloat(math.Round(val)) - } - return nil, nil -} - -func mathSample(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - if take, ok := ensureInt(args[1]); ok { - return math.Sample(vals, int(take)), nil - } - return nil, nil -} - -func mathSpread(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Spread(vals)) -} - -func mathSqrt(ctx context.Context, args ...interface{}) (interface{}, error) { - if val, ok := ensureFloat(args[0]); ok { - return outputFloat(math.Sqrt(val)) - } - return nil, nil -} - -func mathStddev(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.SampleStandardDeviation(vals)) -} - -func mathSum(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Sum(vals)) -} - -func mathTop(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - if take, ok := ensureInt(args[1]); ok { - return math.Top(vals, int(take)), nil - } - return nil, nil -} - -func mathTrimean(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.Trimean(vals)) -} - -func mathVariance(ctx context.Context, args ...interface{}) (interface{}, error) { - vals := ensureFloats(args[0]) - return outputFloat(math.SampleVariance(vals)) -} diff --git a/util/fncs/math_test.go b/util/fncs/math_test.go deleted file mode 100644 index 8b17ce39..00000000 --- a/util/fncs/math_test.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestMath(t *testing.T) { - - var res interface{} - - var test = []interface{}{int(1), int64(3), float32(4.5), float64(3.5)} - var testA = []interface{}{int(1), int64(3), float32(4.5), float64(3.5)} - var testB = []interface{}{int(5), int64(9), float32(2.5), float64(6.5)} - var testC = []interface{}{int(5), int64(5), float32(2.5), float64(6.5)} - - Convey("math.abs() works properly", t, func() { - res, _ = Run(context.Background(), "math.abs", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.abs", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.abs", -1.5) - So(res, ShouldEqual, 1.5) - }) - - Convey("math.bottom() works properly", t, func() { - res, _ = Run(context.Background(), "math.bottom", "test", 2) - So(res, ShouldHaveLength, 0) - res, _ = Run(context.Background(), "math.bottom", testC, "oops") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.bottom", testC, 2) - So(res, ShouldHaveSameTypeAs, []float64{}) - So(res, ShouldContain, 2.5) - So(res, ShouldContain, 5.0) - res, _ = Run(context.Background(), "math.bottom", 13, 2) - So(res, ShouldHaveSameTypeAs, []float64{}) - So(res, ShouldContain, 13.0) - }) - - Convey("math.ceil() works properly", t, func() { - res, _ = Run(context.Background(), "math.ceil", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.ceil", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.ceil", 1.5) - So(res, ShouldEqual, 2) - }) - - Convey("math.correlation() works properly", t, func() { - res, _ = Run(context.Background(), "math.correlation", "test", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.correlation", 1234, 1234) - So(res, ShouldEqual, 0) - res, _ = Run(context.Background(), "math.correlation", testA, testB) - So(res, ShouldEqual, -0.24945922497781908) - }) - - Convey("math.covariance() works properly", t, func() { - res, _ = Run(context.Background(), "math.covariance", "test", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.covariance", 1234, 1234) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.covariance", testA, testB) - So(res, ShouldEqual, -1) - }) - - Convey("math.fixed() works properly", t, func() { - res, _ = Run(context.Background(), "math.fixed", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.fixed", 10, 2) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.fixed", 1.51837461, 2) - So(res, ShouldEqual, 1.52) - }) - - Convey("math.floor() works properly", t, func() { - res, _ = Run(context.Background(), "math.floor", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.floor", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.floor", 1.5) - So(res, ShouldEqual, 1) - }) - - Convey("math.geometricmean() works properly", t, func() { - res, _ = Run(context.Background(), "math.geometricmean", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.geometricmean", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.geometricmean", test) - So(res, ShouldEqual, 2.6218053975140414) - }) - - Convey("math.harmonicmean() works properly", t, func() { - res, _ = Run(context.Background(), "math.harmonicmean", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.harmonicmean", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.harmonicmean", test) - So(res, ShouldEqual, 2.172413793103449) - }) - - Convey("math.interquartile() works properly", t, func() { - res, _ = Run(context.Background(), "math.interquartile", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.interquartile", 10) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.interquartile", test) - So(res, ShouldEqual, 2) - }) - - Convey("math.max() works properly", t, func() { - res, _ = Run(context.Background(), "math.max", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.max", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.max", test) - So(res, ShouldEqual, 4.5) - }) - - Convey("math.mean() works properly", t, func() { - res, _ = Run(context.Background(), "math.mean", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.mean", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.mean", testA, testB) - So(res, ShouldEqual, 3) - }) - - Convey("math.median() works properly", t, func() { - res, _ = Run(context.Background(), "math.median", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.median", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.median", testA, testB) - So(res, ShouldEqual, 3.25) - }) - - Convey("math.midhinge() works properly", t, func() { - res, _ = Run(context.Background(), "math.midhinge", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.midhinge", 10) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.midhinge", test) - So(res, ShouldEqual, 3) - }) - - Convey("math.min() works properly", t, func() { - res, _ = Run(context.Background(), "math.min", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.min", 10) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.min", test) - So(res, ShouldEqual, 1) - }) - - Convey("math.mode() works properly", t, func() { - res, _ = Run(context.Background(), "math.mode", "test") - So(res, ShouldHaveLength, 0) - res, _ = Run(context.Background(), "math.mode", testC) - So(res, ShouldResemble, []float64{5}) - res, _ = Run(context.Background(), "math.mode", 1) - So(res, ShouldResemble, []float64{1}) - }) - - Convey("math.nearestrank() works properly", t, func() { - res, _ = Run(context.Background(), "math.nearestrank", "test", 90) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.nearestrank", 10, "oops") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.nearestrank", 10, 90) - So(res, ShouldEqual, 10) - res, _ = Run(context.Background(), "math.nearestrank", test, 90) - So(res, ShouldEqual, 4.5) - }) - - Convey("math.percentile() works properly", t, func() { - res, _ = Run(context.Background(), "math.percentile", "test", 90) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.percentile", 10, "oops") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.percentile", 10, 90) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.percentile", test, 90) - So(res, ShouldEqual, 4) - }) - - Convey("math.round() works properly", t, func() { - res, _ = Run(context.Background(), "math.round", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.round", 1.4) - So(res, ShouldEqual, 1) - res, _ = Run(context.Background(), "math.round", 1.5) - So(res, ShouldEqual, 2) - }) - - Convey("math.sample() works properly", t, func() { - res, _ = Run(context.Background(), "math.sample", "test", 3) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.sample", 10, "oops") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.sample", 10, 3) - So(res, ShouldResemble, []float64{10}) - res, _ = Run(context.Background(), "math.sample", test, 3) - So(res, ShouldHaveLength, 3) - }) - - Convey("math.spread() works properly", t, func() { - res, _ = Run(context.Background(), "math.spread", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.spread", 10) - So(res, ShouldEqual, 0) - res, _ = Run(context.Background(), "math.spread", test) - So(res, ShouldEqual, 3.5) - }) - - Convey("math.sqrt() works properly", t, func() { - res, _ = Run(context.Background(), "math.sqrt", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.sqrt", test) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.sqrt", 10) - So(res, ShouldEqual, 3.1622776601683795) - }) - - Convey("math.stddev() works properly", t, func() { - res, _ = Run(context.Background(), "math.stddev", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.stddev", 10) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.stddev", test) - So(res, ShouldEqual, 1.4719601443879744) - }) - - Convey("math.sum() works properly", t, func() { - res, _ = Run(context.Background(), "math.sum", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.sum", 1234) - So(res, ShouldEqual, 1234) - res, _ = Run(context.Background(), "math.sum", []interface{}{int(1), int64(3), float32(4.5), float64(3.5)}) - So(res, ShouldEqual, 12) - }) - - Convey("math.top() works properly", t, func() { - res, _ = Run(context.Background(), "math.top", "test", 2) - So(res, ShouldHaveSameTypeAs, []float64{}) - So(res, ShouldHaveLength, 0) - res, _ = Run(context.Background(), "math.top", testC, "oops") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.top", testC, 2) - So(res, ShouldHaveSameTypeAs, []float64{}) - So(res, ShouldContain, 6.5) - So(res, ShouldContain, 5.0) - res, _ = Run(context.Background(), "math.top", 13, 2) - So(res, ShouldHaveSameTypeAs, []float64{}) - So(res, ShouldContain, 13.0) - }) - - Convey("math.trimean() works properly", t, func() { - res, _ = Run(context.Background(), "math.trimean", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.trimean", 10) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.trimean", test) - So(res, ShouldEqual, 3.125) - }) - - Convey("math.variance() works properly", t, func() { - res, _ = Run(context.Background(), "math.variance", "test") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.variance", 10) - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "math.variance", test) - So(res, ShouldEqual, 2.1666666666666665) - }) - -} diff --git a/util/fncs/model.go b/util/fncs/model.go deleted file mode 100644 index cdd13082..00000000 --- a/util/fncs/model.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" -) - -func model(ctx context.Context, args ...interface{}) (interface{}, error) { - - tb, _ := ensureString(args[0]) - - if len(tb) == 0 { - return nil, txn.ErrorTBNotFound - } - - switch len(args) { - case 2: - if max, ok := ensureFloat(args[1]); ok { - return sql.NewModel(tb, 0, 0, max), nil - } - case 3: - if min, ok := ensureFloat(args[1]); ok { - if max, ok := ensureFloat(args[2]); ok { - return sql.NewModel(tb, min, 1, max), nil - } - } - case 4: - if min, ok := ensureFloat(args[1]); ok { - if inc, ok := ensureFloat(args[2]); ok { - if max, ok := ensureFloat(args[3]); ok { - return sql.NewModel(tb, min, inc, max), nil - } - } - } - } - - return nil, nil - -} diff --git a/util/fncs/model_test.go b/util/fncs/model_test.go deleted file mode 100644 index 383a36c7..00000000 --- a/util/fncs/model_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - "github.com/surrealdb/surrealdb/sql" - . "github.com/smartystreets/goconvey/convey" -) - -func TestModel(t *testing.T) { - - var res interface{} - - Convey("model(a) errors properly", t, func() { - res, _ = Run(context.Background(), "model", "test") - So(res, ShouldBeNil) - }) - - Convey("model(a, b) works properly", t, func() { - res, _ = Run(context.Background(), "model", 1, 10) - So(res, ShouldResemble, sql.NewModel("1", 0, 0, 10)) - res, _ = Run(context.Background(), "model", "test", 10) - So(res, ShouldResemble, sql.NewModel("test", 0, 0, 10)) - }) - - Convey("model(a, b, c) works properly", t, func() { - res, _ = Run(context.Background(), "model", 1, 10, 20) - So(res, ShouldResemble, sql.NewModel("1", 10, 1, 20)) - res, _ = Run(context.Background(), "model", "test", 10, 20) - So(res, ShouldResemble, sql.NewModel("test", 10, 1, 20)) - }) - - Convey("model(a, b, c, d) works properly", t, func() { - res, _ = Run(context.Background(), "model", 1, 10, 0.5, 20) - So(res, ShouldResemble, sql.NewModel("1", 10, 0.5, 20)) - res, _ = Run(context.Background(), "model", "test", 10, 0.5, 20) - So(res, ShouldResemble, sql.NewModel("test", 10, 0.5, 20)) - }) - -} diff --git a/util/fncs/purge.go b/util/fncs/purge.go deleted file mode 100644 index 3153a56f..00000000 --- a/util/fncs/purge.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" -) - -func purge(ctx context.Context, args ...interface{}) (interface{}, error) { - if arr, ok := ensureSlice(args[0]); ok { - arr = copySlice(arr) - for i := len(arr) - 1; i >= 0; i-- { - if arr[i] == nil { - copy(arr[i:], arr[i+1:]) - arr[len(arr)-1] = nil - arr = arr[:len(arr)-1] - } - } - return arr, nil - } - if args[0] == nil { - return nil, nil - } - return args[0], nil -} - -func purgeIf(ctx context.Context, args ...interface{}) (interface{}, error) { - if arr, ok := ensureSlice(args[0]); ok { - arr = copySlice(arr) - for i := len(arr) - 1; i >= 0; i-- { - if arr[i] == args[1] { - copy(arr[i:], arr[i+1:]) - arr[len(arr)-1] = nil - arr = arr[:len(arr)-1] - } - } - return arr, nil - } - if args[0] == args[1] { - return nil, nil - } - return args[0], nil -} - -func purgeNot(ctx context.Context, args ...interface{}) (interface{}, error) { - if arr, ok := ensureSlice(args[0]); ok { - arr = copySlice(arr) - for i := len(arr) - 1; i >= 0; i-- { - if arr[i] != args[1] { - copy(arr[i:], arr[i+1:]) - arr[len(arr)-1] = nil - arr = arr[:len(arr)-1] - } - } - return arr, nil - } - if args[0] != args[1] { - return nil, nil - } - return args[0], nil -} diff --git a/util/fncs/purge_test.go b/util/fncs/purge_test.go deleted file mode 100644 index 0f4fe3c6..00000000 --- a/util/fncs/purge_test.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestPurge(t *testing.T) { - - var res interface{} - - var test = []interface{}{int(1), int(2), nil, float64(3.5), "testing string"} - - Convey("purge() works properly", t, func() { - res, _ = Run(context.Background(), "purge", nil) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "purge", "test") - So(res, ShouldResemble, "test") - res, _ = Run(context.Background(), "purge", test) - So(res, ShouldResemble, []interface{}{int(1), int(2), float64(3.5), "testing string"}) - }) - - Convey("purge.if() works properly", t, func() { - res, _ = Run(context.Background(), "purge.if", "test", nil) - So(res, ShouldResemble, "test") - res, _ = Run(context.Background(), "purge.if", "test", "none") - So(res, ShouldResemble, "test") - res, _ = Run(context.Background(), "purge.if", "test", "test") - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "purge.if", test, "testing string") - So(res, ShouldResemble, []interface{}{int(1), int(2), nil, float64(3.5)}) - res, _ = Run(context.Background(), "purge.if", test, 3.5) - So(res, ShouldResemble, []interface{}{int(1), int(2), nil, "testing string"}) - res, _ = Run(context.Background(), "purge.if", test, nil) - So(res, ShouldResemble, []interface{}{int(1), int(2), float64(3.5), "testing string"}) - }) - - Convey("purge.not() works properly", t, func() { - res, _ = Run(context.Background(), "purge.not", "test", nil) - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "purge.not", "test", "none") - So(res, ShouldResemble, nil) - res, _ = Run(context.Background(), "purge.not", "test", "test") - So(res, ShouldResemble, "test") - res, _ = Run(context.Background(), "purge.not", test, "testing string") - So(res, ShouldResemble, []interface{}{"testing string"}) - res, _ = Run(context.Background(), "purge.not", test, 3.5) - So(res, ShouldResemble, []interface{}{float64(3.5)}) - res, _ = Run(context.Background(), "purge.not", test, nil) - So(res, ShouldResemble, []interface{}{nil}) - }) - -} diff --git a/util/fncs/rand.go b/util/fncs/rand.go deleted file mode 100644 index 359e7a0f..00000000 --- a/util/fncs/rand.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/util/fake" -) - -func rand(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.DecimalBetween(0, 1), nil -} - -func randBool(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.Bool(), nil -} - -func randGuid(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.Guid(), nil -} - -func randUuid(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.Uuid(), nil -} - -func randEnum(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return nil, nil - default: - return args[fake.IntegerBetween(0, len(args))], nil - } -} - -func randTime(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 2: - if b, ok := ensureTime(args[0]); ok { - if e, ok := ensureTime(args[1]); ok { - return fake.TimeBetween(b, e), nil - } - } - } - return fake.Time(), nil -} - -func randString(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 1: - if l, ok := ensureInt(args[0]); ok { - return fake.StringLength(int(l)), nil - } - case 2: - if b, ok := ensureInt(args[0]); ok { - if e, ok := ensureInt(args[1]); ok { - return fake.StringBetween(int(b), int(e)), nil - } - } - } - return fake.String(), nil -} - -func randInteger(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 2: - if b, ok := ensureInt(args[0]); ok { - if e, ok := ensureInt(args[1]); ok { - return float64(fake.IntegerBetween(int(b), int(e))), nil - } - } - } - return float64(fake.Integer()), nil -} - -func randDecimal(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 2: - if b, ok := ensureFloat(args[0]); ok { - if e, ok := ensureFloat(args[1]); ok { - return fake.DecimalBetween(b, e), nil - } - } - } - return fake.Decimal(), nil -} - -func randWord(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.Word(), nil -} - -func randSentence(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 2: - if b, ok := ensureInt(args[0]); ok { - if e, ok := ensureInt(args[1]); ok { - return fake.SentenceBetween(int(b), int(e)), nil - } - } - } - return fake.Sentence(), nil -} - -func randParagraph(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 2: - if b, ok := ensureInt(args[0]); ok { - if e, ok := ensureInt(args[1]); ok { - return fake.ParagraphBetween(int(b), int(e)), nil - } - } - } - return fake.Paragraph(), nil -} - -func randPersonEmail(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonEmail(), nil -} - -func randPersonPhone(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonPhone(), nil -} - -func randPersonFullname(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonFullname(), nil -} - -func randPersonFirstname(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonFirstname(), nil -} - -func randPersonLastname(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonLastname(), nil -} - -func randPersonUsername(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonUsername(), nil -} - -func randPersonJobtitle(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.PersonJobtitle(), nil -} - -func randCompanyName(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.CompanyName(), nil -} - -func randCompanyIndustry(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.CompanyIndustry(), nil -} - -func randLocationName(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationName(), nil -} - -func randLocationAddress(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationAddress(), nil -} - -func randLocationStreet(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationStreet(), nil -} - -func randLocationCity(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationCity(), nil -} - -func randLocationState(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationState(), nil -} - -func randLocationCounty(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationCounty(), nil -} - -func randLocationZipcode(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationZipcode(), nil -} - -func randLocationPostcode(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationPostcode(), nil -} - -func randLocationCountry(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationCountry(), nil -} - -func randLocationAltitude(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationAltitude(), nil -} - -func randLocationLatitude(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationLatitude(), nil -} - -func randLocationLongitude(ctx context.Context, args ...interface{}) (interface{}, error) { - return fake.LocationLongitude(), nil -} diff --git a/util/fncs/rand_test.go b/util/fncs/rand_test.go deleted file mode 100644 index fa25d47a..00000000 --- a/util/fncs/rand_test.go +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestRand(t *testing.T) { - - Convey("rand() works properly", t, func() { - res, _ := Run(context.Background(), "rand") - So(res, ShouldHaveSameTypeAs, 36.0) - }) - - Convey("uuid() works properly", t, func() { - res, _ := Run(context.Background(), "uuid") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldHaveLength, 36) - }) - - Convey("rand.bool() works properly", t, func() { - res, _ := Run(context.Background(), "rand.bool") - So(res, ShouldHaveSameTypeAs, true) - }) - - Convey("rand.uuid() works properly", t, func() { - res, _ := Run(context.Background(), "rand.uuid") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldHaveLength, 36) - }) - - Convey("rand.enum() works properly", t, func() { - res, _ := Run(context.Background(), "rand.enum") - So(res, ShouldHaveSameTypeAs, nil) - }) - - Convey("rand.enum(a,b,c) works properly", t, func() { - res, _ := Run(context.Background(), "rand.enum", "one", "two", "tre") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldBeIn, []interface{}{"one", "two", "tre"}) - }) - - Convey("rand.time() works properly", t, func() { - res, _ := Run(context.Background(), "rand.time") - So(res, ShouldHaveSameTypeAs, time.Now()) - }) - - Convey("rand.time(a,b) works properly", t, func() { - d, _ := time.ParseDuration("24h") - now := time.Now() - res, _ := Run(context.Background(), "rand.time", now, now.Add(d)) - So(res, ShouldHaveSameTypeAs, time.Now()) - So(res.(time.Time).UnixNano(), ShouldBeBetween, now.UnixNano(), now.Add(d).UnixNano()) - }) - - Convey("rand.string() works properly", t, func() { - res, _ := Run(context.Background(), "rand.string") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.string(a) works properly", t, func() { - res, _ := Run(context.Background(), "rand.string", int64(12)) - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldHaveLength, 12) - }) - - Convey("rand.string(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "rand.string", int64(12), int64(16)) - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.integer() works properly", t, func() { - res, _ := Run(context.Background(), "rand.integer") - So(res, ShouldHaveSameTypeAs, float64(0)) - }) - - Convey("rand.integer(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "rand.integer", int64(12), int64(16)) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldBeBetween, 11, 17) - }) - - Convey("rand.decimal() works properly", t, func() { - res, _ := Run(context.Background(), "rand.decimal") - So(res, ShouldHaveSameTypeAs, float64(0)) - }) - - Convey("rand.decimal(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "rand.decimal", int64(12), int64(16)) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldBeBetween, 11, 17) - }) - - Convey("rand.word() works properly", t, func() { - res, _ := Run(context.Background(), "rand.word") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.sentence() works properly", t, func() { - res, _ := Run(context.Background(), "rand.sentence") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.sentence(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "rand.sentence", int64(12), int64(16)) - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.paragraph() works properly", t, func() { - res, _ := Run(context.Background(), "rand.paragraph") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.paragraph(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "rand.paragraph", int64(12), int64(16)) - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.person.email works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.email") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldContainSubstring, "@") - }) - - Convey("rand.person.phone works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.phone") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldContainSubstring, " ") - }) - - Convey("rand.person.fullname works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.fullname") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.person.firstname works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.firstname") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.person.lastname works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.lastname") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.person.username works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.username") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.person.jobtitle works properly", t, func() { - res, _ := Run(context.Background(), "rand.person.jobtitle") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.company.name works properly", t, func() { - res, _ := Run(context.Background(), "rand.company.name") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.company.industry works properly", t, func() { - res, _ := Run(context.Background(), "rand.company.industry") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.name works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.name") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.address works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.address") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.street works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.street") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.city works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.city") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.state works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.state") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.county works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.county") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.zipcode works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.zipcode") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.postcode works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.postcode") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.country works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.country") - So(res, ShouldHaveSameTypeAs, "test") - }) - - Convey("rand.location.altitude works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.altitude") - So(res, ShouldHaveSameTypeAs, float64(0)) - }) - - Convey("rand.location.latitude works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.latitude") - So(res, ShouldHaveSameTypeAs, float64(0)) - }) - - Convey("rand.location.longitude works properly", t, func() { - res, _ := Run(context.Background(), "rand.location.longitude") - So(res, ShouldHaveSameTypeAs, float64(0)) - }) - -} diff --git a/util/fncs/regex.go b/util/fncs/regex.go deleted file mode 100644 index 86037064..00000000 --- a/util/fncs/regex.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "regexp" -) - -func regex(ctx context.Context, args ...interface{}) (interface{}, error) { - reg, _ := ensureString(args[0]) - return regexp.Compile(reg) -} diff --git a/util/fncs/regex_test.go b/util/fncs/regex_test.go deleted file mode 100644 index 6ed5949c..00000000 --- a/util/fncs/regex_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "regexp" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestRegex(t *testing.T) { - - var res interface{} - - Convey("regex() works properly", t, func() { - res, _ = Run(context.Background(), "regex", "something") - So(res, ShouldResemble, regexp.MustCompile("something")) - res, _ = Run(context.Background(), "regex", `^[a-z]+\[[0-9]+\]$`) - So(res, ShouldResemble, regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)) - }) - -} diff --git a/util/fncs/scrypt.go b/util/fncs/scrypt.go deleted file mode 100644 index 39a4c67b..00000000 --- a/util/fncs/scrypt.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/elithrar/simple-scrypt" -) - -func scryptCompare(ctx context.Context, args ...interface{}) (interface{}, error) { - if h, ok := ensureString(args[0]); ok { - if s, ok := ensureString(args[1]); ok { - e := scrypt.CompareHashAndPassword([]byte(h), []byte(s)) - if e == nil { - return true, nil - } - } - } - return false, nil -} - -func scryptGenerate(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p := []byte(s) - o := scrypt.DefaultParams - return scrypt.GenerateFromPassword(p, o) -} diff --git a/util/fncs/scrypt_test.go b/util/fncs/scrypt_test.go deleted file mode 100644 index 710c6662..00000000 --- a/util/fncs/scrypt_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestScrypt(t *testing.T) { - - Convey("scrypt.compare(a, b) works properly", t, func() { - res, _ := Run(context.Background(), "scrypt.compare", "16384$8$1$8065a3ec98903c86d950840721ef945b$1f23d0d2ff5528f033161fd21ce84911f9332ac9878953139ad30b6a8c2959f2", "test") - So(res, ShouldEqual, true) - }) - - Convey("scrypt.compare(a, b) errors properly", t, func() { - res, _ := Run(context.Background(), "scrypt.compare", "16384$8$1$8065a3ec98903c86d950840721ef945b$1f23d0d2ff5528f033161fd21ce84911f9332ac9878953139ad30b6a8c2959f2", "wrong") - So(res, ShouldEqual, false) - }) - - Convey("scrypt.generate(a) works properly", t, func() { - res, _ := Run(context.Background(), "scrypt.generate", "test") - So(res, ShouldHaveSameTypeAs, []byte("test")) - }) - -} diff --git a/util/fncs/sets.go b/util/fncs/sets.go deleted file mode 100644 index 6a99f945..00000000 --- a/util/fncs/sets.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" -) - -func difference(ctx context.Context, args ...interface{}) (interface{}, error) { - - d := make([]interface{}, 0) - c := make(map[interface{}]int) - - for _, x := range args { - a, _ := ensureSlice(x) - for _, v := range a { - c[v] += 1 - } - } - - for k, b := range c { - if b == 1 { - d = append(d, k) - } - } - - return d, nil - -} - -func distinct(ctx context.Context, args ...interface{}) (interface{}, error) { - - d := make([]interface{}, 0) - c := make(map[interface{}]bool) - - for _, x := range args { - a, _ := ensureSlice(x) - for _, v := range a { - switch v := v.(type) { - case []interface{}: - for _, v := range v { - c[v] = true - } - default: - c[v] = true - } - } - } - - for k := range c { - d = append(d, k) - } - - return d, nil - -} - -func intersect(ctx context.Context, args ...interface{}) (interface{}, error) { - - l := len(args) - d := make([]interface{}, 0) - c := make(map[interface{}]int) - - for _, x := range args { - a, _ := ensureSlice(x) - for _, v := range a { - c[v] += 1 - } - } - - for k, b := range c { - if b == l { - d = append(d, k) - } - } - - return d, nil - -} - -func union(ctx context.Context, args ...interface{}) (interface{}, error) { - - d := make([]interface{}, 0) - c := make(map[interface{}]bool) - - for _, x := range args { - a, _ := ensureSlice(x) - for _, v := range a { - c[v] = true - } - } - - for k := range c { - d = append(d, k) - } - - return d, nil - -} diff --git a/util/fncs/sets_test.go b/util/fncs/sets_test.go deleted file mode 100644 index e29630e8..00000000 --- a/util/fncs/sets_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestSets(t *testing.T) { - - Convey("difference(a, b, c) works properly", t, func() { - res, _ := Run(context.Background(), "difference", []interface{}{"one"}, []interface{}{"one", "two"}, []interface{}{"one", "two", "tre"}) - So(res, ShouldHaveLength, 1) - So(res, ShouldContain, "tre") - }) - - Convey("distinct(a) works properly", t, func() { - res, _ := Run(context.Background(), "distinct", []interface{}{"one", "two", "two", "tre", "tre", "tre"}) - So(res, ShouldHaveLength, 3) - So(res, ShouldContain, "one") - So(res, ShouldContain, "two") - So(res, ShouldContain, "tre") - }) - - Convey("distinct(a, b, c) works properly", t, func() { - res, _ := Run(context.Background(), "distinct", []interface{}{"one"}, []interface{}{"one", "two"}, []interface{}{"one", "two", "tre"}) - So(res, ShouldHaveLength, 3) - So(res, ShouldContain, "one") - So(res, ShouldContain, "two") - So(res, ShouldContain, "tre") - }) - - Convey("intersect(a, b, c) works properly", t, func() { - res, _ := Run(context.Background(), "intersect", []interface{}{"one"}, []interface{}{"one", "two"}, []interface{}{"one", "two", "tre"}) - So(res, ShouldHaveLength, 1) - So(res, ShouldContain, "one") - }) - - Convey("union(a, b, c) works properly", t, func() { - res, _ := Run(context.Background(), "union", []interface{}{"one"}, []interface{}{"one", "two"}, []interface{}{"one", "two", "tre"}) - So(res, ShouldHaveLength, 3) - So(res, ShouldContain, "one") - So(res, ShouldContain, "two") - So(res, ShouldContain, "tre") - }) - -} diff --git a/util/fncs/string.go b/util/fncs/string.go deleted file mode 100644 index 95c3ebc3..00000000 --- a/util/fncs/string.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "fmt" - "strings" - - "github.com/surrealdb/surrealdb/util/ints" - "github.com/surrealdb/surrealdb/util/slug" - "github.com/surrealdb/surrealdb/util/text" -) - -func stringConcat(ctx context.Context, args ...interface{}) (interface{}, error) { - var str string - for _, v := range args { - str = str + fmt.Sprint(v) - } - return str, nil -} - -func stringContains(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p, _ := ensureString(args[1]) - return strings.Contains(s, p), nil -} - -func stringEndsWith(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p, _ := ensureString(args[1]) - return strings.HasSuffix(s, p), nil -} - -func stringFormat(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0, 1: - // Not enough arguments, so just ignore - default: - s, _ := ensureString(args[0]) - return fmt.Sprintf(s, args[1:]...), nil - } - return nil, nil -} - -func stringIncludes(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p, _ := ensureString(args[1]) - return strings.Contains(s, p), nil -} - -func stringJoin(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0, 1: - // Not enough arguments, so just ignore - default: - var a []string - j, _ := ensureString(args[0]) - for _, v := range args[1:] { - if v != nil { - a = append(a, fmt.Sprint(v)) - } - } - return strings.Join(a, j), nil - } - return nil, nil -} - -func stringLength(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - return float64(len(s)), nil -} - -func stringLevenshtein(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - c, _ := ensureString(args[1]) - return float64(text.Levenshtein(s, c)), nil -} - -func stringLowercase(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - return strings.ToLower(s), nil -} - -func stringRepeat(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - if c, ok := ensureInt(args[1]); ok { - return strings.Repeat(s, int(c)), nil - } - return s, nil -} - -func stringReplace(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - o, _ := ensureString(args[1]) - n, _ := ensureString(args[2]) - return strings.Replace(s, o, n, -1), nil -} - -func stringReverse(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - r := []rune(s) - for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r), nil -} - -func stringSearch(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p, _ := ensureString(args[1]) - return float64(strings.Index(s, p)), nil -} - -func stringSlice(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - b, bk := ensureInt(args[1]) - e, ek := ensureInt(args[2]) - f := ints.Min(len(s), int(b+e)) - if bk && ek { - return s[b:f], nil - } else if bk { - return s[b:], nil - } else if ek { - return s[:f], nil - } - return s, nil -} - -func stringSlug(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 1: - s, _ := ensureString(args[0]) - return slug.Make(s), nil - case 2: - s, _ := ensureString(args[0]) - l, _ := ensureString(args[1]) - return slug.MakeLang(s, l), nil - } - return nil, nil -} - -func stringSplit(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p, _ := ensureString(args[1]) - return strings.Split(s, p), nil -} - -func stringStartsWith(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - p, _ := ensureString(args[1]) - return strings.HasPrefix(s, p), nil -} - -func stringSubstr(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - b, bk := ensureInt(args[1]) - e, ek := ensureInt(args[2]) - f := ints.Min(len(s), int(e)) - if bk && ek { - return s[b:f], nil - } else if bk { - return s[b:], nil - } else if ek { - return s[:f], nil - } - return s, nil -} - -func stringTrim(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - return strings.TrimSpace(s), nil -} - -func stringUppercase(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - return strings.ToUpper(s), nil -} - -func stringWords(ctx context.Context, args ...interface{}) (interface{}, error) { - s, _ := ensureString(args[0]) - return strings.Fields(s), nil -} diff --git a/util/fncs/string_test.go b/util/fncs/string_test.go deleted file mode 100644 index 1ccd1fdb..00000000 --- a/util/fncs/string_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestString(t *testing.T) { - - var res interface{} - - var test = "This IS a test" - var spac = " This IS a test " - - Convey("string.concat() works properly", t, func() { - res, _ = Run(context.Background(), "string.concat", nil, 1, 1.5, "2", true, false) - So(res, ShouldEqual, "11.52truefalse") - }) - - Convey("string.contains() works properly", t, func() { - res, _ = Run(context.Background(), "string.contains", test, "done") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "string.contains", test, "test") - So(res, ShouldEqual, true) - }) - - Convey("string.endsWith() works properly", t, func() { - res, _ = Run(context.Background(), "string.endsWith", test, "done") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "string.endsWith", test, "test") - So(res, ShouldEqual, true) - }) - - Convey("string.format() works properly", t, func() { - res, _ = Run(context.Background(), "string.format", "%.9d", 1) - So(res, ShouldEqual, "000000001") - }) - - Convey("string.format() errors properly", t, func() { - res, _ = Run(context.Background(), "string.format", "%.9d") - So(res, ShouldEqual, nil) - }) - - Convey("string.includes() works properly", t, func() { - res, _ = Run(context.Background(), "string.includes", test, "done") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "string.includes", test, "test") - So(res, ShouldEqual, true) - }) - - Convey("string.join() works properly", t, func() { - res, _ = Run(context.Background(), "string.join") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "string.join", ",") - So(res, ShouldEqual, nil) - res, _ = Run(context.Background(), "string.join", ",", nil, 1, 1.5, "2", true, false) - So(res, ShouldEqual, "1,1.5,2,true,false") - }) - - Convey("string.length() works properly", t, func() { - res, _ = Run(context.Background(), "string.length", test) - So(res, ShouldEqual, 14) - }) - - Convey("string.levenshtein() works properly", t, func() { - res, _ = Run(context.Background(), "string.levenshtein", "test", "test") - So(res, ShouldEqual, 0) - res, _ = Run(context.Background(), "string.levenshtein", "lawn", "flaw") - So(res, ShouldEqual, 2) - res, _ = Run(context.Background(), "string.levenshtein", "test", "done") - So(res, ShouldEqual, 4) - }) - - Convey("string.lowercase() works properly", t, func() { - res, _ = Run(context.Background(), "string.lowercase", test) - So(res, ShouldEqual, "this is a test") - }) - - Convey("string.repeat(a, b) works properly", t, func() { - res, _ = Run(context.Background(), "string.repeat", test, 2) - So(res, ShouldEqual, test+test) - }) - - Convey("string.repeat(a, b) errors properly", t, func() { - res, _ = Run(context.Background(), "string.repeat", test, "test") - So(res, ShouldEqual, test) - }) - - Convey("string.replace() works properly", t, func() { - res, _ = Run(context.Background(), "string.replace", test, "test", "note") - So(res, ShouldEqual, "This IS a note") - }) - - Convey("string.reverse() works properly", t, func() { - res, _ = Run(context.Background(), "string.reverse", test, "test") - So(res, ShouldEqual, "tset a SI sihT") - }) - - Convey("string.search() works properly", t, func() { - res, _ = Run(context.Background(), "string.search", test, "done") - So(res, ShouldEqual, -1) - res, _ = Run(context.Background(), "string.search", test, "test") - So(res, ShouldEqual, 10) - }) - - Convey("string.slice() works properly", t, func() { - res, _ = Run(context.Background(), "string.slice", test, "a", "b") - So(res, ShouldEqual, test) - res, _ = Run(context.Background(), "string.slice", test, "2", "b") - So(res, ShouldEqual, test[2:]) - res, _ = Run(context.Background(), "string.slice", test, "a", "2") - So(res, ShouldEqual, test[:2]) - res, _ = Run(context.Background(), "string.slice", test, "2", "4") - So(res, ShouldEqual, test[2:4+2]) - }) - - Convey("string.split() works properly", t, func() { - res, _ = Run(context.Background(), "string.split", test, " ") - So(res, ShouldResemble, []string{"This", "IS", "a", "test"}) - }) - - Convey("string.startsWith() works properly", t, func() { - res, _ = Run(context.Background(), "string.startsWith", test, "this") - So(res, ShouldEqual, false) - res, _ = Run(context.Background(), "string.startsWith", test, "This") - So(res, ShouldEqual, true) - }) - - Convey("string.substr() works properly", t, func() { - res, _ = Run(context.Background(), "string.substr", test, "a", "b") - So(res, ShouldEqual, test) - res, _ = Run(context.Background(), "string.substr", test, "2", "b") - So(res, ShouldEqual, test[2:]) - res, _ = Run(context.Background(), "string.substr", test, "a", "2") - So(res, ShouldEqual, test[:2]) - res, _ = Run(context.Background(), "string.substr", test, "2", "4") - So(res, ShouldEqual, test[2:4]) - }) - - Convey("string.trim() works properly", t, func() { - res, _ = Run(context.Background(), "string.trim", spac) - So(res, ShouldEqual, test) - }) - - Convey("string.uppercase() works properly", t, func() { - res, _ = Run(context.Background(), "string.uppercase", test) - So(res, ShouldEqual, "THIS IS A TEST") - }) - - Convey("string.words() works properly", t, func() { - res, _ = Run(context.Background(), "string.words", test) - So(res, ShouldResemble, []string{"This", "IS", "a", "test"}) - }) - -} diff --git a/util/fncs/table.go b/util/fncs/table.go deleted file mode 100644 index 66e226fc..00000000 --- a/util/fncs/table.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" -) - -func table(ctx context.Context, args ...interface{}) (interface{}, error) { - - tb, _ := ensureString(args[0]) - - if len(tb) == 0 { - return nil, txn.ErrorTBNotFound - } - - return sql.NewTable(tb), nil - -} diff --git a/util/fncs/table_test.go b/util/fncs/table_test.go deleted file mode 100644 index 620570b9..00000000 --- a/util/fncs/table_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - "github.com/surrealdb/surrealdb/sql" - . "github.com/smartystreets/goconvey/convey" -) - -func TestTable(t *testing.T) { - - var res interface{} - - Convey("table() works properly", t, func() { - res, _ = Run(context.Background(), "table", 1) - So(res, ShouldResemble, sql.NewTable("1")) - res, _ = Run(context.Background(), "table", "test") - So(res, ShouldResemble, sql.NewTable("test")) - }) - -} diff --git a/util/fncs/thing.go b/util/fncs/thing.go deleted file mode 100644 index 03566fa9..00000000 --- a/util/fncs/thing.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" -) - -func thing(ctx context.Context, args ...interface{}) (interface{}, error) { - - tb, _ := ensureString(args[0]) - - if len(tb) == 0 { - return nil, txn.ErrorTBNotFound - } - - return sql.NewThing(tb, args[1]), nil - -} diff --git a/util/fncs/thing_test.go b/util/fncs/thing_test.go deleted file mode 100644 index b4f34260..00000000 --- a/util/fncs/thing_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - "github.com/surrealdb/surrealdb/sql" - . "github.com/smartystreets/goconvey/convey" -) - -func TestThing(t *testing.T) { - - var res interface{} - - Convey("thing() works properly", t, func() { - res, _ = Run(context.Background(), "thing", 1, 1) - So(res, ShouldResemble, sql.NewThing("1", 1)) - res, _ = Run(context.Background(), "thing", "test", 1) - So(res, ShouldResemble, sql.NewThing("test", 1)) - }) - -} diff --git a/util/fncs/time.go b/util/fncs/time.go deleted file mode 100644 index a87bc481..00000000 --- a/util/fncs/time.go +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "time" -) - -func timeNow(ctx context.Context, args ...interface{}) (interface{}, error) { - return time.Now(), nil -} - -func timeAdd(ctx context.Context, args ...interface{}) (interface{}, error) { - if t, ok := ensureTime(args[0]); ok { - if d, ok := ensureDuration(args[1]); ok { - return t.Add(d), nil - } - } - return nil, nil -} - -func timeAge(ctx context.Context, args ...interface{}) (interface{}, error) { - if t, ok := ensureTime(args[0]); ok { - if d, ok := ensureDuration(args[1]); ok { - return t.Add(-d), nil - } - } - return nil, nil -} - -func timeFloor(ctx context.Context, args ...interface{}) (interface{}, error) { - if t, ok := ensureTime(args[0]); ok { - if d, ok := ensureDuration(args[1]); ok { - return t.Truncate(d), nil - } - } - return nil, nil -} - -func timeRound(ctx context.Context, args ...interface{}) (interface{}, error) { - if t, ok := ensureTime(args[0]); ok { - if d, ok := ensureDuration(args[1]); ok { - return t.Round(d), nil - } - } - return nil, nil -} - -func timeDay(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Day()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Day()), nil - } - } - return nil, nil -} - -func timeHour(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Hour()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Hour()), nil - } - } - return nil, nil -} - -func timeMins(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Minute()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Minute()), nil - } - } - return nil, nil -} - -func timeMonth(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Month()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Month()), nil - } - } - return nil, nil -} - -func timeNano(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().UnixNano()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.UnixNano()), nil - } - } - return nil, nil -} - -func timeSecs(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Second()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Second()), nil - } - } - return nil, nil -} - -func timeUnix(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Unix()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Unix()), nil - } - } - return nil, nil -} - -func timeWday(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Weekday()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Weekday()), nil - } - } - return nil, nil -} - -func timeWeek(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - _, w := time.Now().ISOWeek() - return float64(w), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - _, w := v.ISOWeek() - return float64(w), nil - } - } - return nil, nil -} - -func timeYday(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().YearDay()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.YearDay()), nil - } - } - return nil, nil -} - -func timeYear(ctx context.Context, args ...interface{}) (interface{}, error) { - switch len(args) { - case 0: - return float64(time.Now().Year()), nil - case 1: - if v, ok := ensureTime(args[0]); ok { - return float64(v.Year()), nil - } - } - return nil, nil -} diff --git a/util/fncs/time_test.go b/util/fncs/time_test.go deleted file mode 100644 index 61a0108d..00000000 --- a/util/fncs/time_test.go +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestTime(t *testing.T) { - - now := time.Now() - org := time.Unix(0, 0) - dur := 24 * time.Hour - old, _ := time.Parse(time.RFC822Z, time.RFC822Z) - old = old.UTC() - rnd, _ := time.Parse("2006-01-02", "2006-01-03") - rnd = rnd.UTC() - trc, _ := time.Parse("2006-01-02", "2006-01-02") - trc = trc.UTC() - - Convey("time.now() works properly", t, func() { - res, _ := Run(context.Background(), "time.now") - So(res, ShouldHaveSameTypeAs, now) - }) - - Convey("time.add(a, b) works properly", t, func() { - dur, _ := time.ParseDuration("1h") - res, _ := Run(context.Background(), "time.add", now, dur) - So(res, ShouldHaveSameTypeAs, now) - So(res, ShouldHappenAfter, now) - }) - - Convey("time.add(a, b) errors properly", t, func() { - res, _ := Run(context.Background(), "time.add", now, nil) - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.age(a, b) works properly", t, func() { - dur, _ := time.ParseDuration("1h") - res, _ := Run(context.Background(), "time.age", now, dur) - So(res, ShouldHaveSameTypeAs, now) - So(res, ShouldHappenBefore, now) - }) - - Convey("time.age(a, b) errors properly", t, func() { - res, _ := Run(context.Background(), "time.age", now, nil) - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.floor(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "time.floor", old, dur) - So(res, ShouldHaveSameTypeAs, org) - So(res, ShouldEqual, trc) - }) - - Convey("time.floor(a,b) errors properly", t, func() { - res, _ := Run(context.Background(), "time.floor", "one", "two") - So(res, ShouldEqual, nil) - }) - - Convey("time.round(a,b) works properly", t, func() { - res, _ := Run(context.Background(), "time.round", old, dur) - So(res, ShouldHaveSameTypeAs, org) - So(res, ShouldEqual, rnd) - }) - - Convey("time.round(a,b) errors properly", t, func() { - res, _ := Run(context.Background(), "time.round", "one", "two") - So(res, ShouldEqual, nil) - }) - - Convey("time.day() works properly", t, func() { - res, _ := Run(context.Background(), "time.day") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.Day()) - }) - - Convey("time.day(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.day", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 2) - }) - - Convey("time.day(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.day", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.hour() works properly", t, func() { - res, _ := Run(context.Background(), "time.hour") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.Hour()) - }) - - Convey("time.hour(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.hour", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 22) - }) - - Convey("time.hour(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.hour", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.mins() works properly", t, func() { - res, _ := Run(context.Background(), "time.mins") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.Minute()) - }) - - Convey("time.mins(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.mins", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 4) - }) - - Convey("time.mins(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.mins", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.month() works properly", t, func() { - res, _ := Run(context.Background(), "time.month") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.Month()) - }) - - Convey("time.month(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.month", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 1) - }) - - Convey("time.month(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.month", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.nano() works properly", t, func() { - res, _ := Run(context.Background(), "time.nano") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldBeGreaterThanOrEqualTo, now.UnixNano()) - }) - - Convey("time.nano(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.nano", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 1136239440000000000) - }) - - Convey("time.nano(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.nano", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.secs() works properly", t, func() { - res, _ := Run(context.Background(), "time.secs") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.Second()) - }) - - Convey("time.secs(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.secs", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 0) - }) - - Convey("time.secs(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.secs", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.unix() works properly", t, func() { - res, _ := Run(context.Background(), "time.unix") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldBeGreaterThanOrEqualTo, now.Unix()) - }) - - Convey("time.unix(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.unix", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 1136239440) - }) - - Convey("time.unix(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.unix", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.wday() works properly", t, func() { - res, _ := Run(context.Background(), "time.wday") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldBeGreaterThanOrEqualTo, now.Weekday()) - }) - - Convey("time.wday(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.wday", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 1) - }) - - Convey("time.wday(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.wday", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.week() works properly", t, func() { - res, _ := Run(context.Background(), "time.week") - So(res, ShouldHaveSameTypeAs, float64(0)) - _, val := now.ISOWeek() - So(res, ShouldBeGreaterThanOrEqualTo, val) - }) - - Convey("time.week(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.week", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 1) - }) - - Convey("time.week(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.week", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.yday() works properly", t, func() { - res, _ := Run(context.Background(), "time.yday") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.YearDay()) - }) - - Convey("time.yday(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.yday", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 2) - }) - - Convey("time.yday(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.yday", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - - Convey("time.year() works properly", t, func() { - res, _ := Run(context.Background(), "time.year") - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, now.Year()) - }) - - Convey("time.year(a) works properly", t, func() { - res, _ := Run(context.Background(), "time.year", old) - So(res, ShouldHaveSameTypeAs, float64(0)) - So(res, ShouldEqual, 2006) - }) - - Convey("time.year(a,b,c) errors properly", t, func() { - res, _ := Run(context.Background(), "time.year", "one", "two") - So(res, ShouldHaveSameTypeAs, nil) - So(res, ShouldEqual, nil) - }) - -} diff --git a/util/fncs/url.go b/util/fncs/url.go deleted file mode 100644 index 58b41d39..00000000 --- a/util/fncs/url.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "net/url" -) - -func urlHost(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - u, err := url.Parse(v) - if err != nil || !u.IsAbs() { - return "", nil - } - return u.Hostname(), nil -} - -func urlPort(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - u, err := url.Parse(v) - if err != nil || !u.IsAbs() { - return "", nil - } - return u.Port(), nil -} - -func urlPath(ctx context.Context, args ...interface{}) (interface{}, error) { - v, _ := ensureString(args[0]) - u, err := url.Parse(v) - if err != nil || !u.IsAbs() { - return "", nil - } - return u.RequestURI(), nil -} diff --git a/util/fncs/url_test.go b/util/fncs/url_test.go deleted file mode 100644 index 90606549..00000000 --- a/util/fncs/url_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fncs - -import ( - "context" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestUrl(t *testing.T) { - - Convey("url.domain(a) works properly", t, func() { - res, _ := Run(context.Background(), "url.domain", "https://abcum.com:8000/path/to/file") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "abcum.com") - }) - - Convey("url.domain(a) errors properly", t, func() { - res, _ := Run(context.Background(), "url.domain", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "") - }) - - Convey("url.host(a) works properly", t, func() { - res, _ := Run(context.Background(), "url.host", "https://abcum.com:8000/path/to/file") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "abcum.com") - }) - - Convey("url.host(a) errors properly", t, func() { - res, _ := Run(context.Background(), "url.host", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "") - }) - - Convey("url.port(a) works properly", t, func() { - res, _ := Run(context.Background(), "url.port", "https://abcum.com:8000/path/to/file") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "8000") - }) - - Convey("url.port(a) errors properly", t, func() { - res, _ := Run(context.Background(), "url.port", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "") - }) - - Convey("url.path(a) works properly", t, func() { - res, _ := Run(context.Background(), "url.path", "https://abcum.com:8000/path/to/file") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "/path/to/file") - }) - - Convey("url.path(a) errors properly", t, func() { - res, _ := Run(context.Background(), "url.path", "test") - So(res, ShouldHaveSameTypeAs, "test") - So(res, ShouldEqual, "") - }) - -} diff --git a/util/geof/contains.go b/util/geof/contains.go deleted file mode 100644 index 43141def..00000000 --- a/util/geof/contains.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -import ( - "github.com/surrealdb/surrealdb/sql" -) - -func Contains(a *sql.Polygon, b *sql.Point) bool { - beg := len(a.PS) - 1 - end := 0 - contains := raycast(b, a.PS[beg], a.PS[end]) - for i := 1; i < len(a.PS); i++ { - if raycast(b, a.PS[i-1], a.PS[i]) { - contains = !contains - } - } - return contains -} diff --git a/util/geof/geohash.go b/util/geof/geohash.go deleted file mode 100644 index 2b216c76..00000000 --- a/util/geof/geohash.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -import ( - "bytes" - - "github.com/surrealdb/surrealdb/sql" -) - -var bits = []int{16, 8, 4, 2, 1} - -var latmax = []float64{-90, 90} - -var lngmax = []float64{-180, 180} - -var base32 = []byte("0123456789bcdefghjkmnpqrstuvwxyz") - -func refine(interval []float64, cd, mask int) []float64 { - if cd&mask > 0 { - interval[0] = (interval[0] + interval[1]) / 2 - } else { - interval[1] = (interval[0] + interval[1]) / 2 - } - return interval -} - -func GeohashDecode(hash string) *sql.Point { - - isEven := true - lat := latmax - lng := lngmax - latErr := float64(90) - lngErr := float64(180) - var c string - var cd int - - for i := 0; i < len(hash); i++ { - c = hash[i : i+1] - cd = bytes.Index(base32, []byte(c)) - for j := 0; j < 5; j++ { - if isEven { - lngErr /= 2 - lng = refine(lng, cd, bits[j]) - } else { - latErr /= 2 - lat = refine(lat, cd, bits[j]) - } - isEven = !isEven - } - } - - return sql.NewPoint( - (lat[0]+lat[1])/2, - (lng[0]+lng[1])/2, - ) - -} - -func GeohashEncode(point *sql.Point, precision int64) string { - - isEven := true - lat := []float64{-90, 90} - lng := []float64{-180, 180} - bit := 0 - ch := 0 - var geohash bytes.Buffer - var mid float64 - for geohash.Len() < int(precision) { - if isEven { - mid = (lng[0] + lng[1]) / 2 - if point.LO > mid { - ch |= bits[bit] - lng[0] = mid - } else { - lng[1] = mid - } - } else { - mid = (lat[0] + lat[1]) / 2 - if point.LA > mid { - ch |= bits[bit] - lat[0] = mid - } else { - lat[1] = mid - } - } - isEven = !isEven - if bit < 4 { - bit++ - } else { - geohash.WriteByte(base32[ch]) - bit = 0 - ch = 0 - } - } - - return geohash.String() - -} diff --git a/util/geof/haversine.go b/util/geof/haversine.go deleted file mode 100644 index 09fdb9ac..00000000 --- a/util/geof/haversine.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -import ( - "math" - - "github.com/surrealdb/surrealdb/sql" -) - -const earthr float64 = 6371000 - -const radian float64 = math.Pi / 180 - -func Haversine(a, b *sql.Point) float64 { - lata, lnga := a.LA*radian, a.LO*radian - latb, lngb := b.LA*radian, b.LO*radian - latc, lngc := lata-latb, lnga-lngb - dis := math.Pow(math.Sin(latc/2), 2) + math.Cos(lata)*math.Cos(latb)*math.Pow(math.Sin(lngc/2), 2) - c := 2 * math.Atan2(math.Sqrt(dis), math.Sqrt(1-dis)) - return earthr * c -} diff --git a/util/geof/inside.go b/util/geof/inside.go deleted file mode 100644 index 0263f5b0..00000000 --- a/util/geof/inside.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -import ( - "github.com/surrealdb/surrealdb/sql" -) - -func Inside(a *sql.Point, b *sql.Polygon) bool { - beg := len(b.PS) - 1 - end := 0 - contains := raycast(a, b.PS[beg], b.PS[end]) - for i := 1; i < len(b.PS); i++ { - if raycast(a, b.PS[i-1], b.PS[i]) { - contains = !contains - } - } - return contains -} diff --git a/util/geof/intersects.go b/util/geof/intersects.go deleted file mode 100644 index 43a2d81e..00000000 --- a/util/geof/intersects.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -func Intersects(a, b interface{}) bool { - return false -} diff --git a/util/geof/point.go b/util/geof/point.go deleted file mode 100644 index b156178a..00000000 --- a/util/geof/point.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -import ( - "strconv" - - "github.com/surrealdb/surrealdb/sql" -) - -func ensureSlice(args interface{}) (out []interface{}, ok bool) { - if i, ok := args.([]interface{}); ok { - return i, true - } else { - return []interface{}{args}, false - } -} - -func ensureFloats(args interface{}) (out []float64) { - arr, _ := ensureSlice(args) - for _, val := range arr { - switch val := val.(type) { - case int: - out = append(out, float64(val)) - case int64: - out = append(out, float64(val)) - case uint: - out = append(out, float64(val)) - case uint64: - out = append(out, float64(val)) - case float32: - out = append(out, float64(val)) - case float64: - out = append(out, float64(val)) - case string: - if val, err := strconv.ParseFloat(val, 64); err == nil { - out = append(out, float64(val)) - } - } - } - return -} - -func Point(val interface{}) (out *sql.Point, ok bool) { - switch val := val.(type) { - case *sql.Point: - return val, true - case []interface{}: - if p := ensureFloats(val); len(p) == 2 { - return sql.NewPoint(p[0], p[1]), true - } - } - return nil, false -} diff --git a/util/geof/raycast.go b/util/geof/raycast.go deleted file mode 100644 index d66f0062..00000000 --- a/util/geof/raycast.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package geof - -import ( - "math" - - "github.com/surrealdb/surrealdb/sql" -) - -func raycast(point, beg, end *sql.Point) bool { - - // Always ensure that the the first point - // has a Y coordinate that is less than - // the second point. Switch if not. - - if beg.LO > end.LO { - beg, end = end, beg - } - - // Move the point's Y coordinate outside of - // the bounds of the testing region so that - // we can start drawing a ray - for point.LO == beg.LO || point.LO == end.LO { - lng := math.Nextafter(point.LO, math.Inf(1)) - point = sql.NewPoint(point.LA, lng) - } - - // If we are outside of the polygon, indicate so. - if point.LO < beg.LO || point.LO > end.LO { - return false - } - - if beg.LA > end.LA { - if point.LA > beg.LA { - return false - } - if point.LA < end.LA { - return true - } - - } else { - if point.LA > end.LA { - return false - } - if point.LA < beg.LA { - return true - } - } - - raySlope := (point.LO - beg.LO) / (point.LA - beg.LA) - diagSlope := (end.LO - beg.LO) / (end.LA - beg.LA) - - return raySlope >= diagSlope - -} diff --git a/util/guid/guid.go b/util/guid/guid.go deleted file mode 100644 index 05ba2b25..00000000 --- a/util/guid/guid.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package guid - -import ( - "github.com/rs/xid" -) - -type GUID struct { - xid.ID -} - -// NewV1 returns a new GUID. -func New() *GUID { - return &GUID{xid.New()} -} - -func Parse(input string) *GUID { - id, err := xid.FromString(input) - if err != nil { - return nil - } - return &GUID{id} -} diff --git a/util/guid/guid_test.go b/util/guid/guid_test.go deleted file mode 100644 index 1ebc20fa..00000000 --- a/util/guid/guid_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package guid - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestNew(t *testing.T) { - - var str *GUID - - str = New() - - Convey(str.String(), t, func() { - Convey("Should be a GUID", func() { - So(str, ShouldHaveSameTypeAs, &GUID{}) - }) - Convey("Should not be nil", func() { - So(str, ShouldNotBeNil) - }) - Convey("Should be of length 20", func() { - So(str.String(), ShouldHaveLength, 20) - }) - }) - -} - -func TestParsing(t *testing.T) { - - var str *GUID - - str = Parse("thiswillnotbeok5n4g") - - Convey("Parse thiswillnotbeok5n4g", t, func() { - Convey("Should be nil", func() { - So(str, ShouldBeNil) - }) - }) - - str = Parse("9m4e2mr0ui3e8a215n4g") - - Convey("Parse 9m4e2mr0ui3e8a215n4g", t, func() { - Convey("Should be a GUID", func() { - So(str, ShouldHaveSameTypeAs, &GUID{}) - }) - Convey("Should not be nil", func() { - So(str, ShouldNotBeNil) - }) - Convey("Should be of length 20", func() { - So(str.String(), ShouldHaveLength, 20) - }) - Convey("Should be exactly `9m4e2mr0ui3e8a215n4g`", func() { - So(str.String(), ShouldEqual, "9m4e2mr0ui3e8a215n4g") - }) - }) - -} diff --git a/util/hook/hook.go b/util/hook/hook.go deleted file mode 100644 index cbcb7af8..00000000 --- a/util/hook/hook.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package hook - -import ( - "context" - "time" -) - -const ( - Static Kind = iota - Backoff -) - -// Kind specifies the policy type. -type Kind int - -// Policy represents a retryable function policy. -type Policy struct { - // Type is the policy type - Type Kind - // Attempts to retry - Retry int - // Factor is the backoff rate - Factor int - // Sleep is the initial duration to wait before retrying - Sleep time.Duration -} - -// New creates a new static retryable policy, which retries -// after the duration of 'sleep', until the number of retries -// has been reached. -func NewStatic(retry int, sleep time.Duration) *Policy { - return &Policy{ - Type: Static, - Retry: retry, - Sleep: sleep, - } -} - -// New creates a new backoff retryable policy, which increases -// the delay between subsequent retries by the secified factor, -// until the number of retries has been reached. -func NewBackoff(retry, factor int, sleep time.Duration) *Policy { - return &Policy{ - Type: Backoff, - Retry: retry, - Sleep: sleep, - Factor: factor, - } -} - -// Run executes a function until: -// 1. A nil error is returned, -// 2. The max number of retries has been reached, -// 3. The specified context has been cancelled or timedout. -func (p *Policy) Run(ctx context.Context, fnc func() error) error { - - c := make(chan error, 1) - - go func() { c <- p.run(ctx, fnc) }() - - select { - case <-ctx.Done(): - return ctx.Err() - case err := <-c: - return err - } - -} - -func (p *Policy) run(ctx context.Context, fnc func() error) error { - - select { - case <-ctx.Done(): - return ctx.Err() - default: - if err := fnc(); err != nil { - if p.Retry > 0 { - p.sleep() - p.Retry = p.Retry - 1 - return p.run(ctx, fnc) - } - } - } - - return nil - -} - -func (p *Policy) sleep() { - - time.Sleep(p.Sleep) - - if p.Type == Backoff { - p.Sleep = p.Sleep * time.Duration(p.Factor) - } - -} diff --git a/util/indx/indx.go b/util/indx/indx.go deleted file mode 100644 index 4b4f6961..00000000 --- a/util/indx/indx.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package indx - -import ( - "reflect" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" -) - -func Diff(old, now [][]interface{}) (del, add [][]interface{}) { - -loopo: - for _, ov := range old { - for _, nv := range now { - if reflect.DeepEqual(ov, nv) { - continue loopo - } - } - del = append(del, ov) - } - -loopn: - for _, nv := range now { - for _, ov := range old { - if reflect.DeepEqual(ov, nv) { - continue loopn - } - } - add = append(add, nv) - } - - return - -} - -func Build(cols sql.Idents, item *data.Doc) (out [][]interface{}) { - - if len(cols) == 0 { - return [][]interface{}{nil} - } - - col, cols := cols[0], cols[1:] - - sub := Build(cols, item) - - if arr, ok := item.Get(col.VA).Data().([]interface{}); ok { - for _, s := range sub { - for _, a := range arr { - idx := []interface{}{} - idx = append(idx, a) - idx = append(idx, s...) - out = append(out, idx) - } - } - } else { - for _, s := range sub { - idx := []interface{}{} - idx = append(idx, item.Get(col.VA).Data()) - idx = append(idx, s...) - out = append(out, idx) - } - } - - return - -} diff --git a/util/indx/indx_test.go b/util/indx/indx_test.go deleted file mode 100644 index 71f00747..00000000 --- a/util/indx/indx_test.go +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package indx - -import ( - "testing" - - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestDiff(t *testing.T) { - - Convey("Perform diff of same arrays", t, func() { - old := [][]interface{}{ - {"one", "two"}, - {"two", "tre"}, - } - now := [][]interface{}{ - {"one", "two"}, - {"two", "tre"}, - } - So(old, ShouldHaveLength, 2) - So(now, ShouldHaveLength, 2) - del, add := Diff(old, now) - So(del, ShouldHaveLength, 0) - So(del, ShouldResemble, [][]interface{}(nil)) - So(add, ShouldHaveLength, 0) - So(add, ShouldResemble, [][]interface{}(nil)) - }) - - Convey("Perform diff of reversed arrays", t, func() { - old := [][]interface{}{ - {"one", "two"}, - {"two", "tre"}, - } - now := [][]interface{}{ - {"two", "tre"}, - {"one", "two"}, - } - So(old, ShouldHaveLength, 2) - So(now, ShouldHaveLength, 2) - del, add := Diff(old, now) - So(del, ShouldHaveLength, 0) - So(del, ShouldResemble, [][]interface{}(nil)) - So(add, ShouldHaveLength, 0) - So(add, ShouldResemble, [][]interface{}(nil)) - }) - - Convey("Perform diff of same and different arrays", t, func() { - old := [][]interface{}{ - {"one", "two"}, - {"two", "tre"}, - } - now := [][]interface{}{ - {"two", "tre"}, - {"one", "tre"}, - } - So(old, ShouldHaveLength, 2) - So(now, ShouldHaveLength, 2) - del, add := Diff(old, now) - So(del, ShouldHaveLength, 1) - So(del, ShouldResemble, [][]interface{}{{"one", "two"}}) - So(add, ShouldHaveLength, 1) - So(add, ShouldResemble, [][]interface{}{{"one", "tre"}}) - }) - - Convey("Perform diff of same and different length arrays", t, func() { - old := [][]interface{}{ - {"one", "two"}, - {"two", "tre"}, - {"one", "tre"}, - } - now := [][]interface{}{ - {"two", "tre"}, - } - So(old, ShouldHaveLength, 3) - So(now, ShouldHaveLength, 1) - del, add := Diff(old, now) - So(del, ShouldHaveLength, 2) - So(del, ShouldResemble, [][]interface{}{{"one", "two"}, {"one", "tre"}}) - So(add, ShouldHaveLength, 0) - So(add, ShouldResemble, [][]interface{}(nil)) - }) - -} - -func TestBuild(t *testing.T) { - - Convey("Perform build with missing fields", t, func() { - - col := sql.Idents{ - sql.NewIdent("one"), - sql.NewIdent("two"), - } - - doc := data.Consume(map[string]interface{}{ - "tre": "TRE", - }) - - out := Build(col, doc) - - So(out, ShouldResemble, [][]interface{}{ - {nil, nil}, - }) - - }) - - Convey("Perform build with existing fields", t, func() { - - col := sql.Idents{ - sql.NewIdent("one"), - sql.NewIdent("two"), - } - - doc := data.Consume(map[string]interface{}{ - "one": "ONE", - "two": "TWO", - }) - - out := Build(col, doc) - - So(out, ShouldResemble, [][]interface{}{ - {"ONE", "TWO"}, - }) - - }) - - Convey("Perform build with subfield array fields", t, func() { - - col := sql.Idents{ - sql.NewIdent("one"), - sql.NewIdent("two"), - sql.NewIdent("arr"), - } - - doc := data.Consume(map[string]interface{}{ - "one": "ONE", - "two": "TWO", - "arr": []interface{}{1, 2, 3}, - }) - - out := Build(col, doc) - - So(out, ShouldResemble, [][]interface{}{ - {"ONE", "TWO", 1}, - {"ONE", "TWO", 2}, - {"ONE", "TWO", 3}, - }) - - }) - - Convey("Perform build with empty array field", t, func() { - - col := sql.Idents{ - sql.NewIdent("test.*"), - } - - doc := data.Consume(map[string]interface{}{ - "test": []interface{}{}, - }) - - out := Build(col, doc) - - So(out, ShouldResemble, [][]interface{}(nil)) - - }) - - Convey("Perform build with non-empty array field", t, func() { - - col := sql.Idents{ - sql.NewIdent("test.*"), - } - - doc := data.Consume(map[string]interface{}{ - "test": []interface{}{"one", "two", "tre"}, - }) - - out := Build(col, doc) - - So(out, ShouldResemble, [][]interface{}{ - {"one"}, - {"two"}, - {"tre"}, - }) - - }) - -} diff --git a/util/ints/ints.go b/util/ints/ints.go deleted file mode 100644 index 05ce5712..00000000 --- a/util/ints/ints.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ints - -func Min(min int, vals ...int) int { - for _, val := range vals { - if val < min { - min = val - } - } - return min -} - -func Max(max int, vals ...int) int { - for _, val := range vals { - if val > max { - max = val - } - } - return max -} - -func Below(cen, val int) int { - if val < cen { - return val - } - return cen -} - -func Above(cen, val int) int { - if val > cen { - return val - } - return cen -} - -func Between(min, max, val int) int { - switch { - case val < min: - return min - case val > max: - return max - default: - return val - } -} diff --git a/util/ints/ints_test.go b/util/ints/ints_test.go deleted file mode 100644 index d1308e97..00000000 --- a/util/ints/ints_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ints - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestDiff(t *testing.T) { - - Convey("Check minimum", t, func() { - So(Min(15, 37, 10, 23), ShouldEqual, 10) - So(Min(15, 37, 16, 23), ShouldEqual, 15) - }) - - Convey("Check maximum", t, func() { - So(Max(15, 37, 10, 23), ShouldEqual, 37) - So(Max(40, 37, 16, 23), ShouldEqual, 40) - }) - - Convey("Check below", t, func() { - So(Below(20, 10), ShouldEqual, 10) - So(Below(20, 20), ShouldEqual, 20) - So(Below(20, 30), ShouldEqual, 20) - }) - - Convey("Check above", t, func() { - So(Above(20, 10), ShouldEqual, 20) - So(Above(20, 20), ShouldEqual, 20) - So(Above(20, 30), ShouldEqual, 30) - }) - - Convey("Check between", t, func() { - So(Between(1, 1, 0), ShouldEqual, 1) - So(Between(1, 1, 1), ShouldEqual, 1) - So(Between(1, 1, 2), ShouldEqual, 1) - So(Between(1, 10, 0), ShouldEqual, 1) - So(Between(1, 10, 1), ShouldEqual, 1) - So(Between(1, 10, 5), ShouldEqual, 5) - So(Between(1, 10, 10), ShouldEqual, 10) - So(Between(1, 10, 15), ShouldEqual, 10) - }) - -} diff --git a/util/keys/database.go b/util/keys/database.go deleted file mode 100644 index be808348..00000000 --- a/util/keys/database.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Database ... -type Database struct { - KV string - NS string - DB string -} - -// init initialises the key -func (k *Database) init() *Database { - return k -} - -// Copy creates a copy of the key -func (k *Database) Copy() *Database { - return &Database{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - } -} - -// Encode encodes the key into binary -func (k *Database) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB) -} - -// Decode decodes the key from binary -func (k *Database) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB) -} - -// String returns a string representation of the key -func (k *Database) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB) -} diff --git a/util/keys/db.go b/util/keys/db.go deleted file mode 100644 index da219542..00000000 --- a/util/keys/db.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// DB ... -type DB struct { - KV string - NS string - DB string -} - -// init initialises the key -func (k *DB) init() *DB { - return k -} - -// Copy creates a copy of the key -func (k *DB) Copy() *DB { - return &DB{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - } -} - -// Encode encodes the key into binary -func (k *DB) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "!", "d", k.DB) -} - -// Decode decodes the key from binary -func (k *DB) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &__, &k.DB) -} - -// String returns a string representation of the key -func (k *DB) String() string { - k.init() - return output(k.KV, "*", k.NS, "!", "d", k.DB) -} diff --git a/util/keys/decode.go b/util/keys/decode.go deleted file mode 100644 index cd6a19e9..00000000 --- a/util/keys/decode.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import ( - "sync" - "time" -) - -type decoder struct { - r *reader -} - -var decoders = sync.Pool{ - New: func() interface{} { - return &decoder{ - r: newReader(), - } - }, -} - -// decode decodes an encoded string using the unicode collation algorithm. -func decode(data []byte, items ...interface{}) { - dec := newDecoder(data) - dec.Decode(items...) - dec.Reset() - return -} - -func newDecoder(b []byte) *decoder { - d := decoders.Get().(*decoder) - d.r.r.ResetBytes(b) - return d -} - -func (d *decoder) Reset() { - decoders.Put(d) -} - -func (d *decoder) Decode(items ...interface{}) { - - for _, item := range items { - - switch value := item.(type) { - - case *time.Time: - *value = d.r.readTime() - - case *bool: - *value = d.r.readBool() - - case *[]byte: - *value = d.r.readBytes() - - case *string: - *value = d.r.readString() - - case *int: - *value = int(d.r.readFloat()) - - case *int8: - *value = int8(d.r.readFloat()) - - case *int16: - *value = int16(d.r.readFloat()) - - case *int32: - *value = int32(d.r.readFloat()) - - case *int64: - *value = int64(d.r.readFloat()) - - case *uint: - *value = uint(d.r.readFloat()) - - case *uint8: - *value = uint8(d.r.readFloat()) - - case *uint16: - *value = uint16(d.r.readFloat()) - - case *uint32: - *value = uint32(d.r.readFloat()) - - case *uint64: - *value = uint64(d.r.readFloat()) - - case *float32: - *value = float32(d.r.readFloat()) - - case *float64: - *value = float64(d.r.readFloat()) - - case *[]time.Time: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, d.r.readTime()) - } - } - - case *[]bool: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, d.r.readBool()) - } - } - - case *[]string: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, d.r.readString()) - } - } - - case *[]int: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, int(d.r.readFloat())) - } - } - - case *[]int8: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, int8(d.r.readFloat())) - } - } - - case *[]int16: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, int16(d.r.readFloat())) - } - } - - case *[]int32: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, int32(d.r.readFloat())) - } - } - - case *[]int64: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, int64(d.r.readFloat())) - } - } - - case *[]uint: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, uint(d.r.readFloat())) - } - } - - case *[]uint16: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, uint16(d.r.readFloat())) - } - } - - case *[]uint32: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, uint32(d.r.readFloat())) - } - } - - case *[]uint64: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, uint64(d.r.readFloat())) - } - } - - case *[]float32: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, float32(d.r.readFloat())) - } - } - - case *[]float64: - if d.r.readNext(bARR) { - for !d.r.readNext(bEND) { - *value = append(*value, float64(d.r.readFloat())) - } - } - - case *[]interface{}: - *value = d.r.readArray() - - case *interface{}: - - switch d.r.lookNext() { - default: - *value = d.r.readAny() - case bNIL: - *value = d.r.readNull() - case bVAL: - *value = d.r.readBool() - case bTME: - *value = d.r.readTime() - case bNEG, bPOS: - *value = d.r.readFloat() - case bSTR, bPRE, bSUF: - *value = d.r.readString() - case bARR: - *value = d.r.readArray() - - } - - } - - } - -} diff --git a/util/keys/dt.go b/util/keys/dt.go deleted file mode 100644 index fea2b1ce..00000000 --- a/util/keys/dt.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// DT ... -type DT struct { - KV string - NS string - DB string - TK string -} - -// init initialises the key -func (k *DT) init() *DT { - return k -} - -// Copy creates a copy of the key -func (k *DT) Copy() *DT { - return &DT{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TK: k.TK, - } -} - -// Encode encodes the key into binary -func (k *DT) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "!", "k", k.TK) -} - -// Decode decodes the key from binary -func (k *DT) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &__, &k.TK) -} - -// String returns a string representation of the key -func (k *DT) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "!", "k", k.TK) -} diff --git a/util/keys/du.go b/util/keys/du.go deleted file mode 100644 index f921a796..00000000 --- a/util/keys/du.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// DU ... -type DU struct { - KV string - NS string - DB string - US string -} - -// init initialises the key -func (k *DU) init() *DU { - return k -} - -// Copy creates a copy of the key -func (k *DU) Copy() *DU { - return &DU{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - US: k.US, - } -} - -// Encode encodes the key into binary -func (k *DU) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "!", "u", k.US) -} - -// Decode decodes the key from binary -func (k *DU) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &__, &k.US) -} - -// String returns a string representation of the key -func (k *DU) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "!", "u", k.US) -} diff --git a/util/keys/edge.go b/util/keys/edge.go deleted file mode 100644 index 19057a8b..00000000 --- a/util/keys/edge.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Edge ... -type Edge struct { - KV string - NS string - DB string - TB string - ID interface{} - TK string - TP string - FT string - FK interface{} -} - -// init initialises the key -func (k *Edge) init() *Edge { - switch k.TK { - case "«»": - case "‹", "›": - case "«", "»": - default: - k.TK = "«»" - } - return k -} - -// Copy creates a copy of the key -func (k *Edge) Copy() *Edge { - return &Edge{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - ID: k.ID, - TK: k.TK, - TP: k.TP, - FT: k.FT, - FK: k.FK, - } -} - -// Encode encodes the key into binary -func (k *Edge) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "*", k.ID, k.TK, k.TP, k.FT, k.FK) -} - -// Decode decodes the key from binary -func (k *Edge) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &k.ID, &k.TK, &k.TP, &k.FT, &k.FK) -} - -// String returns a string representation of the key -func (k *Edge) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "*", k.ID, k.TK, k.TP, k.FT, k.FK) -} diff --git a/util/keys/encode.go b/util/keys/encode.go deleted file mode 100644 index b6ed4bab..00000000 --- a/util/keys/encode.go +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import ( - "sync" - "time" -) - -type encoder struct { - w *writer -} - -var encoders = sync.Pool{ - New: func() interface{} { - return &encoder{ - w: newWriter(), - } - }, -} - -// Encode encodes an interface using the unicode collation algorithm. -func Encode(items ...interface{}) []byte { - return encode(items...) -} - -// encode encodes an interface using the unicode collation algorithm. -func encode(items ...interface{}) (dst []byte) { - enc := newEncoder(&dst) - enc.Encode(items...) - enc.Reset() - return -} - -func newEncoder(b *[]byte) *encoder { - e := encoders.Get().(*encoder) - e.w.w.ResetBytes(b) - return e -} - -func (e *encoder) Reset() { - encoders.Put(e) -} - -func (e *encoder) Encode(items ...interface{}) { - - for _, item := range items { - - switch value := item.(type) { - - case nil: - - e.w.writeOne(bNIL) - e.w.writeOne(bEND) - - case bool: - - e.w.writeOne(bVAL) - if value { - e.w.writeOne(bVAL) - } - e.w.writeOne(bEND) - - case time.Time: - - e.w.writeOne(bTME) - e.w.writeTime(value) - e.w.writeOne(bEND) - - case []byte: - - e.w.writeOne(bSTR) - e.w.writeMany(value) - e.w.writeOne(bEND) - e.w.writeOne(bEND) - - case string: - - if value == Ignore { - break - } - - if value == Prefix { - e.w.writeOne(bPRE) - e.w.writeOne(bEND) - break - } - - if value == Suffix { - e.w.writeOne(bSUF) - e.w.writeOne(bEND) - break - } - - e.w.writeOne(bSTR) - e.w.writeString(value) - e.w.writeOne(bEND) - e.w.writeOne(bEND) - - case int: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case int8: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case int16: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case int32: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case int64: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case uint: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case uint8: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case uint16: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case uint32: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case uint64: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case float32: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case float64: - - e.w.writeFloat(float64(value)) - e.w.writeOne(bEND) - - case []time.Time: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []bool: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []string: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []int: - - e.w.writeOne(bARR) - for _, val := range value { - e.w.writeFloat(float64(val)) - e.w.writeOne(bEND) - } - e.w.writeOne(bEND) - - case []int8: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []int16: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []int32: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []int64: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []uint: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []uint16: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []uint32: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []uint64: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []float32: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []float64: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - case []interface{}: - - e.w.writeOne(bARR) - for _, val := range value { - e.Encode(val) - } - e.w.writeOne(bEND) - - } - - } - -} diff --git a/util/keys/ev.go b/util/keys/ev.go deleted file mode 100644 index c44b280f..00000000 --- a/util/keys/ev.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// EV ... -type EV struct { - KV string - NS string - DB string - TB string - EV string -} - -// init initialises the key -func (k *EV) init() *EV { - return k -} - -// Copy creates a copy of the key -func (k *EV) Copy() *EV { - return &EV{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - EV: k.EV, - } -} - -// Encode encodes the key into binary -func (k *EV) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "e", k.EV) -} - -// Decode decodes the key from binary -func (k *EV) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &__, &k.EV) -} - -// String returns a string representation of the key -func (k *EV) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "e", k.EV) -} diff --git a/util/keys/fd.go b/util/keys/fd.go deleted file mode 100644 index 55a1c3c8..00000000 --- a/util/keys/fd.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// FD ... -type FD struct { - KV string - NS string - DB string - TB string - FD string -} - -// init initialises the key -func (k *FD) init() *FD { - return k -} - -// Copy creates a copy of the key -func (k *FD) Copy() *FD { - return &FD{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - FD: k.FD, - } -} - -// Encode encodes the key into binary -func (k *FD) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "f", k.FD) -} - -// Decode decodes the key from binary -func (k *FD) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &__, &k.FD) -} - -// String returns a string representation of the key -func (k *FD) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "f", k.FD) -} diff --git a/util/keys/field.go b/util/keys/field.go deleted file mode 100644 index dcf76c56..00000000 --- a/util/keys/field.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Field ... -type Field struct { - KV string - NS string - DB string - TB string - ID interface{} - FD string -} - -// init initialises the key -func (k *Field) init() *Field { - return k -} - -// Copy creates a copy of the key -func (k *Field) Copy() *Field { - return &Field{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - ID: k.ID, - FD: k.FD, - } -} - -// Encode encodes the key into binary -func (k *Field) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "*", k.ID, "*", k.FD) -} - -// Decode decodes the key from binary -func (k *Field) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &k.ID, &__, &k.FD) -} - -// String returns a string representation of the key -func (k *Field) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "*", k.ID, "*", k.FD) -} diff --git a/util/keys/ft.go b/util/keys/ft.go deleted file mode 100644 index 6558e0db..00000000 --- a/util/keys/ft.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// FT ... -type FT struct { - KV string - NS string - DB string - TB string - FT string -} - -// init initialises the key -func (k *FT) init() *FT { - return k -} - -func (k *FT) Copy() *FT { - return &FT{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - FT: k.FT, - } -} - -// Encode encodes the key into binary -func (k *FT) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "t", k.FT) -} - -// Decode decodes the key from binary -func (k *FT) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &__, &k.FT) -} - -// String returns a string representation of the key -func (k *FT) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "t", k.FT) -} diff --git a/util/keys/full_test.go b/util/keys/full_test.go deleted file mode 100644 index 9d7cabf2..00000000 --- a/util/keys/full_test.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import "time" - -type Full struct { - N interface{} // nil - B bool // true - F bool // false - S string // string - T time.Time // time.Time - NI64 int64 // negative int64 - NI32 int32 // negative int32 - NI16 int16 // negative int16 - NI8 int8 // negative int8 - NI int // negative int - I int // positive int - I8 int8 // positive int8 - I16 int16 // positive int16 - I32 int32 // positive int32 - I64 int64 // positive int64 - UI uint // positive uint - UI8 uint8 // positive uint8 - UI16 uint16 // positive uint16 - UI32 uint32 // positive uint32 - UI64 uint64 // positive uint64 - NF64 float64 // negative float64 - NF32 float32 // negative float32 - F32 float32 // positive float32 - F64 float64 // positive float64 - AB []bool // bool array - AS []string // string array - AT []time.Time // time array - AI []int // int array - AI8 []int8 // int8 array - AI16 []int16 // int16 array - AI32 []int32 // int32 array - AI64 []int64 // int64 array - AUI []uint // uint array - AUI8 []uint8 // uint8 array - AUI16 []uint16 // uint16 array - AUI32 []uint32 // uint32 array - AUI64 []uint64 // uint64 array - AF32 []float32 // float32 array - AF64 []float64 // float64 array - IN interface{} // interface{} - IB interface{} // interface{} true - IF interface{} // interface{} false - IT interface{} // interface{} time.Time - II interface{} // interface{} number - ID interface{} // interface{} double - INA interface{} // interface{} array - AIN []interface{} // []interface{} array -} - -func (f *Full) Copy() Key { - return &Full{ - N: f.N, - B: f.B, - F: f.F, - S: f.S, - T: f.T, - NI64: f.NI64, - NI32: f.NI32, - NI16: f.NI16, - NI8: f.NI8, - NI: f.NI, - I: f.I, - I8: f.I8, - I16: f.I16, - I32: f.I32, - I64: f.I64, - UI: f.UI, - UI8: f.UI8, - UI16: f.UI16, - UI32: f.UI32, - UI64: f.UI64, - NF64: f.NF64, - NF32: f.NF32, - F32: f.F32, - F64: f.F64, - AB: f.AB, - AS: f.AS, - AT: f.AT, - AI: f.AI, - AI8: f.AI8, - AI16: f.AI16, - AI32: f.AI32, - AI64: f.AI64, - AUI: f.AUI, - AUI8: f.AUI8, - AUI16: f.AUI16, - AUI32: f.AUI32, - AUI64: f.AUI64, - AF32: f.AF32, - AF64: f.AF64, - IN: f.IN, - IB: f.IB, - IF: f.IF, - IT: f.IT, - II: f.II, - ID: f.ID, - INA: f.INA, - AIN: f.AIN, - } -} - -func (f *Full) String() (s string) { - return "Test key" -} - -func (f *Full) Encode() []byte { - - return encode( - f.N, f.B, f.F, f.S, f.T, - f.NI64, f.NI32, f.NI16, f.NI8, f.NI, - f.I, f.I8, f.I16, f.I32, f.I64, - f.UI, f.UI8, f.UI16, f.UI32, f.UI64, - f.NF64, f.NF32, f.F32, f.F64, - f.AB, f.AS, f.AT, - f.AI, f.AI8, f.AI16, f.AI32, f.AI64, - f.AUI, f.AUI8, f.AUI16, f.AUI32, f.AUI64, - f.AF32, f.AF64, - f.IN, f.IB, f.IF, f.IT, f.II, f.ID, f.INA, f.AIN, - ) - -} - -func (f *Full) Decode(data []byte) { - - decode( - data, - &f.N, &f.B, &f.F, &f.S, &f.T, - &f.NI64, &f.NI32, &f.NI16, &f.NI8, &f.NI, - &f.I, &f.I8, &f.I16, &f.I32, &f.I64, - &f.UI, &f.UI8, &f.UI16, &f.UI32, &f.UI64, - &f.NF64, &f.NF32, &f.F32, &f.F64, - &f.AB, &f.AS, &f.AT, - &f.AI, &f.AI8, &f.AI16, &f.AI32, &f.AI64, - &f.AUI, &f.AUI8, &f.AUI16, &f.AUI32, &f.AUI64, - &f.AF32, &f.AF64, - &f.IN, &f.IB, &f.IF, &f.IT, &f.II, &f.ID, &f.INA, &f.AIN, - ) - -} diff --git a/util/keys/index.go b/util/keys/index.go deleted file mode 100644 index 824e236d..00000000 --- a/util/keys/index.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Index ... -type Index struct { - KV string - NS string - DB string - TB string - IX string - FD interface{} -} - -// init initialises the key -func (k *Index) init() *Index { - return k -} - -// Copy creates a copy of the key -func (k *Index) Copy() *Index { - return &Index{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - IX: k.IX, - FD: k.FD, - } -} - -// Encode encodes the key into binary -func (k *Index) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "¤", k.IX, k.FD) -} - -// Decode decodes the key from binary -func (k *Index) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &k.IX, &k.FD) -} - -// String returns a string representation of the key -func (k *Index) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "¤", k.IX, k.FD) -} diff --git a/util/keys/ix.go b/util/keys/ix.go deleted file mode 100644 index b7338453..00000000 --- a/util/keys/ix.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// IX ... -type IX struct { - KV string - NS string - DB string - TB string - IX string -} - -// init initialises the key -func (k *IX) init() *IX { - return k -} - -// Copy creates a copy of the key -func (k *IX) Copy() *IX { - return &IX{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - IX: k.IX, - } -} - -// Encode encodes the key into binary -func (k *IX) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "i", k.IX) -} - -// Decode decodes the key from binary -func (k *IX) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &__, &k.IX) -} - -// String returns a string representation of the key -func (k *IX) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "i", k.IX) -} diff --git a/util/keys/keys.go b/util/keys/keys.go deleted file mode 100644 index ee44df37..00000000 --- a/util/keys/keys.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import "time" - -const ( - // Ignore specifies an ignored field - Ignore = ignore - // Prefix is the lowest char found in a key - Prefix = prefix - // Suffix is the highest char found in a key - Suffix = suffix - // Ignore specifies an ignored field - ignore = "\x00" - // Prefix is the lowest char found in a key - prefix = "\x01" - // Suffix is the highest char found in a key - suffix = "\xff" -) - -var ( - // StartOfTime is a datetime in the past - StartOfTime = time.Unix(0, 0) - // EndOfTime is a datetime in the future - EndOfTime = time.Now().AddDate(50, 0, 0) -) - -var ( - bEND = byte(0x00) - bPRE = byte(0x01) - bNIL = byte(0x02) - bVAL = byte(0x03) - bTME = byte(0x04) - bNEG = byte(0x05) - bPOS = byte(0x06) - bSTR = byte(0x07) - bARR = byte(0x08) - bSUF = byte(0x09) -) - -const ( - // MinNumber is the minimum number which can be accurately serialized - MinNumber = -1 << 53 - // MaxNumber is the maximum number which can be accurately serialized - MaxNumber = 1<<53 - 1 -) - -// Key ... -type Key interface { - String() string - Encode() []byte - Decode(data []byte) -} diff --git a/util/keys/keys_test.go b/util/keys/keys_test.go deleted file mode 100644 index 25f6e1b6..00000000 --- a/util/keys/keys_test.go +++ /dev/null @@ -1,551 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import ( - "bytes" - "fmt" - "math" - "reflect" - "testing" - "time" - - . "github.com/smartystreets/goconvey/convey" -) - -var sorts []Key - -var tests []struct { - str string - obj Key - new Key -} - -var prefs []struct { - obj Key - yes []Key - nos []Key -} - -func ShouldPrefix(actual interface{}, expected ...interface{}) string { - if bytes.HasPrefix(expected[0].([]byte), actual.([]byte)) { - return "" - } else { - return fmt.Sprintf("%v was not prefixed by \n%v\n%s\n%s", expected[0], actual, expected[0], actual) - } -} - -func ShouldNotPrefix(actual interface{}, expected ...interface{}) string { - if bytes.HasPrefix(expected[0].([]byte), actual.([]byte)) { - return fmt.Sprintf("%v was prefixed by \n%v\n%s\n%s", expected[0], actual, expected[0], actual) - } else { - return "" - } -} - -func ShouldSortBefore(actual interface{}, expected ...interface{}) string { - if bytes.Compare(actual.([]byte), expected[0].([]byte)) > 0 { - return fmt.Sprintf("%v should sort before \n%v\n%s\n%s", actual, expected[0], actual, expected[0]) - } else { - return "" - } -} - -func ShouldSortAfter(actual interface{}, expected ...interface{}) string { - if bytes.Compare(actual.([]byte), expected[0].([]byte)) < 0 { - return fmt.Sprintf("%v should sort after \n%v\n%s\n%s", actual, expected[0], actual, expected[0]) - } else { - return "" - } -} - -func TestMain(t *testing.T) { - - clock, _ := time.Parse(time.RFC3339, "1987-06-22T08:00:00.123456789Z") - - tests = []struct { - str string - obj Key - new Key - }{ - { - str: "/surreal", - obj: &KV{KV: "surreal"}, - new: &KV{}, - }, - { - str: "/surreal/!/n/abcum", - obj: &NS{KV: "surreal", NS: "abcum"}, - new: &NS{}, - }, - { - str: "/surreal/*/abcum", - obj: &Namespace{KV: "surreal", NS: "abcum"}, - new: &Namespace{}, - }, - { - str: "/surreal/*/abcum/!/d/database", - obj: &DB{KV: "surreal", NS: "abcum", DB: "database"}, - new: &DB{}, - }, - { - str: "/surreal/*/abcum/!/k/default", - obj: &NT{KV: "surreal", NS: "abcum", TK: "default"}, - new: &NT{}, - }, - { - str: "/surreal/*/abcum/!/u/info@abcum.com", - obj: &NU{KV: "surreal", NS: "abcum", US: "info@abcum.com"}, - new: &NU{}, - }, - { - str: "/surreal/*/abcum/*/database", - obj: &Database{KV: "surreal", NS: "abcum", DB: "database"}, - new: &Database{}, - }, - { - str: "/surreal/*/abcum/*/database/!/k/default", - obj: &DT{KV: "surreal", NS: "abcum", DB: "database", TK: "default"}, - new: &DT{}, - }, - { - str: "/surreal/*/abcum/*/database/!/s/admin", - obj: &SC{KV: "surreal", NS: "abcum", DB: "database", SC: "admin"}, - new: &SC{}, - }, - { - str: "/surreal/*/abcum/*/database/!/st/admin/!/k/default", - obj: &ST{KV: "surreal", NS: "abcum", DB: "database", SC: "admin", TK: "default"}, - new: &ST{}, - }, - { - str: "/surreal/*/abcum/*/database/!/t/person", - obj: &TB{KV: "surreal", NS: "abcum", DB: "database", TB: "person"}, - new: &TB{}, - }, - { - str: "/surreal/*/abcum/*/database/!/u/info@abcum.com", - obj: &DU{KV: "surreal", NS: "abcum", DB: "database", US: "info@abcum.com"}, - new: &DU{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person", - obj: &Table{KV: "surreal", NS: "abcum", DB: "database", TB: "person"}, - new: &Table{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/!/e/trigger", - obj: &EV{KV: "surreal", NS: "abcum", DB: "database", TB: "person", EV: "trigger"}, - new: &EV{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/!/f/fullname", - obj: &FD{KV: "surreal", NS: "abcum", DB: "database", TB: "person", FD: "fullname"}, - new: &FD{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/!/i/teenagers", - obj: &IX{KV: "surreal", NS: "abcum", DB: "database", TB: "person", IX: "teenagers"}, - new: &IX{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/!/l/realtime", - obj: &LV{KV: "surreal", NS: "abcum", DB: "database", TB: "person", LV: "realtime"}, - new: &LV{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/!/t/foreign", - obj: &FT{KV: "surreal", NS: "abcum", DB: "database", TB: "person", FT: "foreign"}, - new: &FT{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/\x01", - obj: &Thing{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: Prefix}, - new: &Thing{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/873c2f37-ea03-4c5e-843e-cf393af44155", - obj: &Thing{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155"}, - new: &Thing{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/873c2f37-ea03-4c5e-843e-cf393af44155/*/name.first", - obj: &Field{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155", FD: "name.first"}, - new: &Field{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/873c2f37-ea03-4c5e-843e-cf393af44155/*/name.last", - obj: &Field{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155", FD: "name.last"}, - new: &Field{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/873c2f37-ea03-4c5e-843e-cf393af44155/«/clicked/link/b38d7aa1-60d6-4f2d-8702-46bd0fa961fe", - obj: &Edge{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155", TK: "«", TP: "clicked", FT: "link", FK: "b38d7aa1-60d6-4f2d-8702-46bd0fa961fe"}, - new: &Edge{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/873c2f37-ea03-4c5e-843e-cf393af44155/«»/clicked/link/b38d7aa1-60d6-4f2d-8702-46bd0fa961fe", - obj: &Edge{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155", TK: "«»", TP: "clicked", FT: "link", FK: "b38d7aa1-60d6-4f2d-8702-46bd0fa961fe"}, - new: &Edge{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/873c2f37-ea03-4c5e-843e-cf393af44155/»/clicked/link/b38d7aa1-60d6-4f2d-8702-46bd0fa961fe", - obj: &Edge{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155", TK: "»", TP: "clicked", FT: "link", FK: "b38d7aa1-60d6-4f2d-8702-46bd0fa961fe"}, - new: &Edge{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/*/\xff", - obj: &Thing{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: Suffix}, - new: &Thing{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/~/873c2f37-ea03-4c5e-843e-cf393af44155/1987-06-22T08:00:00.123456789Z", - obj: &Patch{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "873c2f37-ea03-4c5e-843e-cf393af44155", AT: clock}, - new: &Patch{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/~/test/1987-06-22T08:00:00.123456789Z", - obj: &Patch{KV: "surreal", NS: "abcum", DB: "database", TB: "person", ID: "test", AT: clock}, - new: &Patch{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/¤/names/[false account:1 lastname firstname]", - obj: &Index{KV: "surreal", NS: "abcum", DB: "database", TB: "person", IX: "names", FD: []interface{}{false, "account:1", "lastname", nil, "firstname"}}, - new: &Index{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/¤/names/[lastname firstname]", - obj: &Index{KV: "surreal", NS: "abcum", DB: "database", TB: "person", IX: "names", FD: []interface{}{"lastname", "firstname"}}, - new: &Index{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/¤/names/[lastname firstname]/873c2f37-ea03-4c5e-843e-cf393af44155", - obj: &Point{KV: "surreal", NS: "abcum", DB: "database", TB: "person", IX: "names", FD: []interface{}{"lastname", "firstname"}, ID: "873c2f37-ea03-4c5e-843e-cf393af44155"}, - new: &Point{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/¤/uniqs/[false account:1 lastname firstname]/873c2f37-ea03-4c5e-843e-cf393af44155", - obj: &Point{KV: "surreal", NS: "abcum", DB: "database", TB: "person", IX: "uniqs", FD: []interface{}{false, "account:1", "lastname", nil, "firstname"}, ID: "873c2f37-ea03-4c5e-843e-cf393af44155"}, - new: &Point{}, - }, - { - str: "/surreal/*/abcum/*/database/*/person/¤/uniqs/[lastname firstname]/873c2f37-ea03-4c5e-843e-cf393af44155", - obj: &Point{KV: "surreal", NS: "abcum", DB: "database", TB: "person", IX: "uniqs", FD: []interface{}{"lastname", "firstname"}, ID: "873c2f37-ea03-4c5e-843e-cf393af44155"}, - new: &Point{}, - }, - { - str: "Test key", - new: &Full{}, - obj: &Full{ - N: nil, - B: true, - F: false, - S: "Test", - T: clock, - NI64: int64(MinNumber), - NI32: math.MinInt32, - NI16: math.MinInt16, - NI8: math.MinInt8, - NI: -1, - I: 1, - I8: math.MaxInt8, - I16: math.MaxInt16, - I32: math.MaxInt32, - I64: int64(MaxNumber), - UI: 1, - UI8: math.MaxUint8, - UI16: math.MaxUint16, - UI32: math.MaxUint32, - UI64: uint64(MaxNumber), - NF64: -math.MaxFloat64, - NF32: -math.MaxFloat32, - F32: math.MaxFloat32, - F64: math.MaxFloat64, - AB: []bool{true, false}, - AS: []string{"A", "B", "C"}, - AT: []time.Time{clock, clock, clock}, - AI: []int{1}, - AI8: []int8{math.MaxInt8}, - AI16: []int16{math.MaxInt16}, - AI32: []int32{math.MaxInt32}, - AI64: []int64{int64(MaxNumber)}, - AUI: []uint{1}, - AUI8: []uint8{math.MaxUint8}, - AUI16: []uint16{math.MaxUint16}, - AUI32: []uint32{math.MaxUint32}, - AUI64: []uint64{uint64(MaxNumber)}, - AF32: []float32{1.1, 1.2, 1.3}, - AF64: []float64{1.1, 1.2, 1.3}, - IN: "Test", - IB: true, - IF: false, - IT: clock, - II: float64(19387.1), - ID: float64(183784.13413), - INA: []interface{}{true, false, nil, "Test", clock, int64(192), 1.1, 1.2, 1.3}, - AIN: []interface{}{true, false, nil, "Test", clock, int64(192), 1.1, 1.2, 1.3, []interface{}{"Test"}}, - }, - }, - } - - sorts = []Key{ - - &Table{KV: "kv", NS: "ns", DB: "db", TB: "person"}, - - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Prefix}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: nil}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: false}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: true}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: -9223372036854775807}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: -2147483647}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: -32767}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: -12}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: -2}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: -1}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 0}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 1}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 2}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 12}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 127}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: int8(math.MaxInt8)}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 32767}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: int16(math.MaxInt16)}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 2147483647}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: int32(math.MaxInt32)}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: 9223372036854775807}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: int64(math.MaxInt64)}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "A"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "B"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "Bb"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "C"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "a"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "b"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "bB"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "c"}, - &Edge{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test1", TP: "friend", FK: int8(2)}, - &Edge{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test1", TP: "friend", FK: int8(3)}, - &Edge{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test2", TP: "friend", FK: int8(1)}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "z"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "Â"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "Ä"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "ß"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "â"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "ä"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "①"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "会"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "😀😀😀"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Suffix}, - - &Patch{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: int8(1), AT: time.Now()}, - &Patch{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: int8(1), AT: time.Now()}, - - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: Prefix}, - - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:abcum", false, "Smith", nil, "Zoe"}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:abcum", true, "Morgan Hitchcock", nil, "Tobie"}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:abcum", true, "Rutherford", nil, "Sam"}}, - - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:tests", false, "Smith", nil, "Zoe"}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:tests", true, "Morgan Hitchcock", nil, "Tobie"}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:tests", true, "Rutherford", nil, "Sam"}}, - - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 0, 127}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 0, 127}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 1, math.MaxInt8}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 2, math.MaxInt16}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 2, math.MaxInt32}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 2, MaxNumber}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"account:zymba", 2, MaxNumber}}, - - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: Suffix}, - } - - prefs = []struct { - obj Key - yes []Key - nos []Key - }{ - { - obj: &Namespace{KV: "kv", NS: "ns"}, - yes: []Key{ - &Thing{KV: "kv", NS: "ns", DB: "other", TB: "person", ID: "test"}, - &Table{KV: "kv", NS: "ns", DB: "db", TB: "person"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Prefix}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Suffix}, - &Patch{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test", AT: clock}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"1", "2"}}, - &Point{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"3", "4"}}, - }, - nos: []Key{ - &Thing{KV: "kv", NS: "other", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "other", NS: "ns", DB: "db", TB: "person", ID: "test"}, - }, - }, - { - obj: &Database{KV: "kv", NS: "ns", DB: "db"}, - yes: []Key{ - &Table{KV: "kv", NS: "ns", DB: "db", TB: "person"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Prefix}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Suffix}, - &Patch{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test", AT: clock}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"1", "2"}}, - &Point{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"3", "4"}}, - }, - nos: []Key{ - &Thing{KV: "kv", NS: "ns", DB: "other", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "other", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "other", NS: "ns", DB: "db", TB: "person", ID: "test"}, - }, - }, - { - obj: &Table{KV: "kv", NS: "ns", DB: "db", TB: "person"}, - yes: []Key{ - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Prefix}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Suffix}, - &Patch{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test", AT: clock}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"1", "2"}}, - &Point{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"3", "4"}}, - }, - nos: []Key{ - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "other", ID: "test"}, - &Thing{KV: "kv", NS: "ns", DB: "other", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "other", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "other", NS: "ns", DB: "db", TB: "person", ID: "test"}, - }, - }, - { - obj: &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Ignore}, - yes: []Key{ - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Prefix}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: Suffix}, - }, - nos: []Key{ - &Patch{KV: "kv", NS: "ns", DB: "db", TB: "person", ID: "test", AT: clock}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"1", "2"}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"3", "4"}}, - &Thing{KV: "kv", NS: "ns", DB: "db", TB: "other", ID: "test"}, - &Thing{KV: "kv", NS: "ns", DB: "other", TB: "person", ID: "test"}, - &Thing{KV: "kv", NS: "other", DB: "db", TB: "person", ID: "test"}, - &Thing{KV: "other", NS: "ns", DB: "db", TB: "person", ID: "test"}, - }, - }, - { - obj: &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: Ignore}, - yes: []Key{ - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"1", "2"}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{"3", "4"}}, - }, - nos: []Key{ - &Index{KV: "kv", NS: "ns", DB: "db", TB: "person", IX: "other", FD: []interface{}{}}, - &Index{KV: "kv", NS: "ns", DB: "db", TB: "other", IX: "names", FD: []interface{}{}}, - &Index{KV: "kv", NS: "ns", DB: "other", TB: "person", IX: "names", FD: []interface{}{}}, - &Index{KV: "kv", NS: "other", DB: "db", TB: "person", IX: "names", FD: []interface{}{}}, - &Index{KV: "other", NS: "ns", DB: "db", TB: "person", IX: "names", FD: []interface{}{}}, - }, - }, - } - -} - -func TestCopying(t *testing.T) { - - for _, test := range tests { - - Convey(test.str, t, func() { - val := reflect.ValueOf(test.obj).MethodByName("Copy").Call([]reflect.Value{}) - So(val[0].Interface(), ShouldResemble, test.obj) - }) - - } - -} - -func TestDisplaying(t *testing.T) { - - for _, test := range tests { - - Convey(test.str, t, func() { - So(test.obj.String(), ShouldEqual, test.str) - }) - - } - -} - -func TestEncoding(t *testing.T) { - - for i, test := range tests { - - Convey(test.str, t, func() { - - enc := test.obj.Encode() - test.new.Decode(enc) - - So(test.new, ShouldResemble, test.obj) - - if i > 0 && i < len(tests)-1 { - old := tests[i-1].obj.Encode() - So(old, ShouldSortBefore, enc) - } - - }) - - } - -} - -func TestPrefixing(t *testing.T) { - - for _, test := range prefs { - - Convey(test.obj.String(), t, func() { - - for _, key := range test.yes { - Convey("Key "+test.obj.String()+" should prefix "+key.String(), func() { - So(test.obj.Encode(), ShouldPrefix, key.Encode()) - }) - } - - for _, key := range test.nos { - Convey("Key "+test.obj.String()+" should not prefix "+key.String(), func() { - So(test.obj.Encode(), ShouldNotPrefix, key.Encode()) - }) - } - - }) - - } - -} - -func TestSorting(t *testing.T) { - - for i := 1; i < len(sorts); i++ { - - txt := fmt.Sprintf("%#v", sorts[i-1]) - - Convey(txt, t, func() { - one := sorts[i-1].Encode() - two := sorts[i].Encode() - So(one, ShouldSortBefore, two) - }) - - } - -} diff --git a/util/keys/kv.go b/util/keys/kv.go deleted file mode 100644 index cda5194f..00000000 --- a/util/keys/kv.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// KV ... -type KV struct { - KV string -} - -// init initialises the key -func (k *KV) init() *KV { - return k -} - -// Copy creates a copy of the key -func (k *KV) Copy() *KV { - return &KV{ - KV: k.KV, - } -} - -// Encode encodes the key into binary -func (k *KV) Encode() []byte { - k.init() - return encode(k.KV) -} - -// Decode decodes the key from binary -func (k *KV) Decode(data []byte) { - k.init() - decode(data, &k.KV) -} - -// String returns a string representation of the key -func (k *KV) String() string { - k.init() - return output(k.KV) -} diff --git a/util/keys/lv.go b/util/keys/lv.go deleted file mode 100644 index b45f7498..00000000 --- a/util/keys/lv.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// LV ... -type LV struct { - KV string - NS string - DB string - TB string - LV string -} - -// init initialises the key -func (k *LV) init() *LV { - return k -} - -// Copy creates a copy of the key -func (k *LV) Copy() *LV { - return &LV{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - LV: k.LV, - } -} - -// Encode encodes the key into binary -func (k *LV) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "l", k.LV) -} - -// Decode decodes the key from binary -func (k *LV) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &__, &k.LV) -} - -// String returns a string representation of the key -func (k *LV) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "!", "l", k.LV) -} diff --git a/util/keys/namespace.go b/util/keys/namespace.go deleted file mode 100644 index 594f22d4..00000000 --- a/util/keys/namespace.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Namespace ... -type Namespace struct { - KV string - NS string -} - -// init initialises the key -func (k *Namespace) init() *Namespace { - return k -} - -// Copy creates a copy of the key -func (k *Namespace) Copy() *Namespace { - return &Namespace{ - KV: k.KV, - NS: k.NS, - } -} - -// Encode encodes the key into binary -func (k *Namespace) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS) -} - -// Decode decodes the key from binary -func (k *Namespace) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS) -} - -// String returns a string representation of the key -func (k *Namespace) String() string { - k.init() - return output(k.KV, "*", k.NS) -} diff --git a/util/keys/ns.go b/util/keys/ns.go deleted file mode 100644 index f0e6e7c1..00000000 --- a/util/keys/ns.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// NS ... -type NS struct { - KV string - NS string -} - -// init initialises the key -func (k *NS) init() *NS { - return k -} - -// Copy creates a copy of the key -func (k *NS) Copy() *NS { - return &NS{ - KV: k.KV, - NS: k.NS, - } -} - -// Encode encodes the key into binary -func (k *NS) Encode() []byte { - k.init() - return encode(k.KV, "!", "n", k.NS) -} - -// Decode decodes the key from binary -func (k *NS) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &__, &k.NS) -} - -// String returns a string representation of the key -func (k *NS) String() string { - k.init() - return output(k.KV, "!", "n", k.NS) -} diff --git a/util/keys/nt.go b/util/keys/nt.go deleted file mode 100644 index f2344cb0..00000000 --- a/util/keys/nt.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// NT ... -type NT struct { - KV string - NS string - TK string -} - -// init initialises the key -func (k *NT) init() *NT { - return k -} - -// Copy creates a copy of the key -func (k *NT) Copy() *NT { - return &NT{ - KV: k.KV, - NS: k.NS, - TK: k.TK, - } -} - -// Encode encodes the key into binary -func (k *NT) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "!", "k", k.TK) -} - -// Decode decodes the key from binary -func (k *NT) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &__, &k.TK) -} - -// String returns a string representation of the key -func (k *NT) String() string { - k.init() - return output(k.KV, "*", k.NS, "!", "k", k.TK) -} diff --git a/util/keys/nu.go b/util/keys/nu.go deleted file mode 100644 index 6f7cd336..00000000 --- a/util/keys/nu.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// NU ... -type NU struct { - KV string - NS string - US string -} - -// init initialises the key -func (k *NU) init() *NU { - return k -} - -// Copy creates a copy of the key -func (k *NU) Copy() *NU { - return &NU{ - KV: k.KV, - NS: k.NS, - US: k.US, - } -} - -// Encode encodes the key into binary -func (k *NU) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "!", "u", k.US) -} - -// Decode decodes the key from binary -func (k *NU) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &__, &k.US) -} - -// String returns a string representation of the key -func (k *NU) String() string { - k.init() - return output(k.KV, "*", k.NS, "!", "u", k.US) -} diff --git a/util/keys/output.go b/util/keys/output.go deleted file mode 100644 index 3aa6ad31..00000000 --- a/util/keys/output.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import "fmt" - -// output decodes an encoded string using the unicode collation algorithm. -func output(items ...interface{}) (out string) { - for _, v := range items { - out = out + fmt.Sprintf("/%v", v) - } - return -} diff --git a/util/keys/patch.go b/util/keys/patch.go deleted file mode 100644 index 19282698..00000000 --- a/util/keys/patch.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import ( - "time" -) - -// Patch ... -type Patch struct { - KV string - NS string - DB string - TB string - ID interface{} - AT time.Time -} - -// init initialises the key -func (k *Patch) init() *Patch { - if k.AT.IsZero() { - k.AT = time.Now() - } - return k -} - -// Copy creates a copy of the key -func (k *Patch) Copy() *Patch { - return &Patch{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - ID: k.ID, - AT: k.AT, - } -} - -// Encode encodes the key into binary -func (k *Patch) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "~", k.ID, k.AT) -} - -// Decode decodes the key from binary -func (k *Patch) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &k.ID, &k.AT) -} - -// String returns a string representation of the key -func (k *Patch) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "~", k.ID, k.AT.Format(time.RFC3339Nano)) -} diff --git a/util/keys/point.go b/util/keys/point.go deleted file mode 100644 index a3126baf..00000000 --- a/util/keys/point.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Point ... -type Point struct { - KV string - NS string - DB string - TB string - IX string - FD interface{} - ID interface{} -} - -// init initialises the key -func (k *Point) init() *Point { - return k -} - -// Copy creates a copy of the key -func (k *Point) Copy() *Point { - return &Point{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - IX: k.IX, - FD: k.FD, - ID: k.ID, - } -} - -// Encode encodes the key into binary -func (k *Point) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "¤", k.IX, k.FD, k.ID) -} - -// Decode decodes the key from binary -func (k *Point) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &k.IX, &k.FD, &k.ID) -} - -// String returns a string representation of the key -func (k *Point) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "¤", k.IX, k.FD, k.ID) -} diff --git a/util/keys/reader.go b/util/keys/reader.go deleted file mode 100644 index 466dcf83..00000000 --- a/util/keys/reader.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import ( - "encoding/binary" - "math" - "time" - - "github.com/surrealdb/bump" -) - -type reader struct { - r *bump.Reader -} - -func newReader() *reader { - return &reader{ - r: bump.NewReader(nil), - } -} - -func (r *reader) unread() { - -} - -func (r *reader) lookNext() (byt byte) { - byt, _ = r.r.PeekByte() - return -} - -func (r *reader) readNext(exp byte) (fnd bool) { - if byt, _ := r.r.PeekByte(); byt == exp { - r.r.ReadByte() - return true - } - return false -} - -func (r *reader) readSize(sze int) (byt []byte) { - byt, _ = r.r.ReadBytes(sze) - return byt -} - -func (r *reader) readUpto(exp ...byte) (byt []byte) { - -LOOP: - for { - - bit, _ := r.r.ReadByte() - byt = append(byt, bit) - if bit != exp[0] { - continue - } - - for j := 1; j < len(exp); j++ { - if r.readNext(exp[j]) { - byt = append(byt, bit) - continue - } - break LOOP - } - - break - - } - - return byt[:len(byt)-len(exp)] - -} - -// -------------------------------------------------- -// -------------------------------------------------- -// -------------------------------------------------- -// -------------------------------------------------- -// -------------------------------------------------- - -func (r *reader) readAny() (val interface{}) { - return r.readUpto(bEND) -} - -func (r *reader) readNull() (val interface{}) { - if r.readNext(bNIL) { - r.readNext(bEND) - } - return -} - -func (r *reader) readTime() (val time.Time) { - if r.readNext(bTME) { - bin := r.readSize(8) - dec := binary.BigEndian.Uint64(bin) - val = time.Unix(0, int64(dec)).UTC() - r.readNext(bEND) - } - return -} - -func (r *reader) readBool() (val bool) { - if r.readNext(bVAL) { - val = r.readNext(bVAL) - r.readNext(bEND) - } - return -} - -func (r *reader) readBytes() (val []byte) { - if r.readNext(bSTR) { - val = r.readUpto(bEND, bEND) - } - return -} - -func (r *reader) readFloat() (val float64) { - if r.readNext(bNEG) { - bin := r.readSize(8) - dec := binary.BigEndian.Uint64(bin) - val = math.Float64frombits(^dec) - r.readNext(bEND) - } else if r.readNext(bPOS) { - bin := r.readSize(8) - dec := binary.BigEndian.Uint64(bin) - val = math.Float64frombits(dec) - r.readNext(bEND) - } - return -} - -func (r *reader) readString() (val string) { - if r.readNext(bSTR) { - val = string(r.readUpto(bEND, bEND)) - } else if r.readNext(bPRE) { - val = Prefix - r.readNext(bEND) - } else if r.readNext(bSUF) { - val = Suffix - r.readNext(bEND) - } - return -} - -func (r *reader) readNumber() (val interface{}) { - var num float64 - if r.readNext(bNEG) { - bin := r.readSize(8) - dec := binary.BigEndian.Uint64(bin) - num = math.Float64frombits(^dec) - r.readNext(bEND) - } else if r.readNext(bPOS) { - bin := r.readSize(8) - dec := binary.BigEndian.Uint64(bin) - num = math.Float64frombits(dec) - r.readNext(bEND) - } - if math.Trunc(num) == num { - return int64(math.Trunc(num)) - } - return num -} - -func (r *reader) readArray() (val []interface{}) { - if r.readNext(bARR) { - for !r.readNext(bEND) { - switch r.lookNext() { - default: - val = append(val, []interface{}{r.readAny()}...) - case bNIL: - val = append(val, []interface{}{r.readNull()}...) - case bVAL: - val = append(val, []interface{}{r.readBool()}...) - case bTME: - val = append(val, []interface{}{r.readTime()}...) - case bNEG, bPOS: - val = append(val, []interface{}{r.readNumber()}...) - case bSTR, bPRE, bSUF: - val = append(val, []interface{}{r.readString()}...) - case bARR: - val = append(val, []interface{}{r.readArray()}...) - } - } - r.readNext(bEND) - } - return -} diff --git a/util/keys/sc.go b/util/keys/sc.go deleted file mode 100644 index 3df779fe..00000000 --- a/util/keys/sc.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// SC ... -type SC struct { - KV string - NS string - DB string - SC string -} - -// init initialises the key -func (k *SC) init() *SC { - return k -} - -// Copy creates a copy of the key -func (k *SC) Copy() *SC { - return &SC{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - SC: k.SC, - } -} - -// Encode encodes the key into binary -func (k *SC) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "!", "s", k.SC) -} - -// Decode decodes the key from binary -func (k *SC) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &__, &k.SC) -} - -// String returns a string representation of the key -func (k *SC) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "!", "s", k.SC) -} diff --git a/util/keys/st.go b/util/keys/st.go deleted file mode 100644 index 28de7129..00000000 --- a/util/keys/st.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// ST ... -type ST struct { - KV string - NS string - DB string - SC string - TK string -} - -// init initialises the key -func (k *ST) init() *ST { - return k -} - -// Copy creates a copy of the key -func (k *ST) Copy() *ST { - return &ST{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - SC: k.SC, - TK: k.TK, - } -} - -// Encode encodes the key into binary -func (k *ST) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "!", "st", k.SC, "!", "k", k.TK) -} - -// Decode decodes the key from binary -func (k *ST) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &__, &k.SC, &__, &__, &k.TK) -} - -// String returns a string representation of the key -func (k *ST) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "!", "st", k.SC, "!", "k", k.TK) -} diff --git a/util/keys/table.go b/util/keys/table.go deleted file mode 100644 index ea4b7784..00000000 --- a/util/keys/table.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Table ... -type Table struct { - KV string - NS string - DB string - TB string -} - -// init initialises the key -func (k *Table) init() *Table { - return k -} - -// Copy creates a copy of the key -func (k *Table) Copy() *Table { - return &Table{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - } -} - -// Encode encodes the key into binary -func (k *Table) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB) -} - -// Decode decodes the key from binary -func (k *Table) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB) -} - -// String returns a string representation of the key -func (k *Table) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB) -} diff --git a/util/keys/tb.go b/util/keys/tb.go deleted file mode 100644 index 14a6c85c..00000000 --- a/util/keys/tb.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// TB ... -type TB struct { - KV string - NS string - DB string - TB string -} - -// init initialises the key -func (k *TB) init() *TB { - return k -} - -// Copy creates a copy of the key -func (k *TB) Copy() *TB { - return &TB{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - } -} - -// Encode encodes the key into binary -func (k *TB) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "!", "t", k.TB) -} - -// Decode decodes the key from binary -func (k *TB) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &__, &k.TB) -} - -// String returns a string representation of the key -func (k *TB) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "!", "t", k.TB) -} diff --git a/util/keys/thing.go b/util/keys/thing.go deleted file mode 100644 index 5a63eade..00000000 --- a/util/keys/thing.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -// Thing ... -type Thing struct { - KV string - NS string - DB string - TB string - ID interface{} -} - -// init initialises the key -func (k *Thing) init() *Thing { - return k -} - -// Copy creates a copy of the key -func (k *Thing) Copy() *Thing { - return &Thing{ - KV: k.KV, - NS: k.NS, - DB: k.DB, - TB: k.TB, - ID: k.ID, - } -} - -// Encode encodes the key into binary -func (k *Thing) Encode() []byte { - k.init() - return encode(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "*", k.ID) -} - -// Decode decodes the key from binary -func (k *Thing) Decode(data []byte) { - k.init() - var __ string - decode(data, &k.KV, &__, &k.NS, &__, &k.DB, &__, &k.TB, &__, &k.ID) -} - -// String returns a string representation of the key -func (k *Thing) String() string { - k.init() - return output(k.KV, "*", k.NS, "*", k.DB, "*", k.TB, "*", k.ID) -} diff --git a/util/keys/writer.go b/util/keys/writer.go deleted file mode 100644 index 7304c40b..00000000 --- a/util/keys/writer.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package keys - -import ( - "encoding/binary" - "math" - "time" - - "github.com/surrealdb/bump" -) - -type writer struct { - w *bump.Writer -} - -func newWriter() *writer { - return &writer{ - w: bump.NewWriter(nil), - } -} - -func (w *writer) writeOne(v byte) { - w.w.WriteByte(v) -} - -func (w *writer) writeMany(v []byte) { - w.w.WriteBytes(v) -} - -func (w *writer) writeTime(v time.Time) { - b := make([]byte, 8) - binary.BigEndian.PutUint64(b, uint64(v.UTC().UnixNano())) - w.w.WriteBytes(b) -} - -func (w *writer) writeFloat(v float64) { - b := make([]byte, 8) - if v < 0 { - w.w.WriteByte(bNEG) - binary.BigEndian.PutUint64(b, ^math.Float64bits(v)) - } else { - w.w.WriteByte(bPOS) - binary.BigEndian.PutUint64(b, math.Float64bits(v)) - } - w.w.WriteBytes(b) -} - -func (w *writer) writeString(v string) { - w.w.WriteString(v) -} diff --git a/util/lang/lang.go b/util/lang/lang.go deleted file mode 100644 index 689db645..00000000 --- a/util/lang/lang.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package lang - -import ( - "regexp" - "strings" -) - -type inflection struct { - regexp *regexp.Regexp - replace string -} - -// Regular is a regexp find replace inflection -type Regular struct { - find string - replace string -} - -// Irregular is a hard replace inflection, -// containing both singular and plural forms -type Irregular struct { - singular string - plural string -} - -// RegularSlice is a slice of Regular inflections -type RegularSlice []Regular - -// IrregularSlice is a slice of Irregular inflections -type IrregularSlice []Irregular - -var pluralInflections = RegularSlice{ - {"([a-z])$", "${1}s"}, - {"s$", "s"}, - {"^(ax|test)is$", "${1}es"}, - {"(octop|vir)us$", "${1}i"}, - {"(octop|vir)i$", "${1}i"}, - {"(alias|status)$", "${1}es"}, - {"(bu)s$", "${1}ses"}, - {"(buffal|tomat)o$", "${1}oes"}, - {"([ti])um$", "${1}a"}, - {"([ti])a$", "${1}a"}, - {"sis$", "ses"}, - {"(?:([^f])fe|([lr])f)$", "${1}${2}ves"}, - {"(hive)$", "${1}s"}, - {"([^aeiouy]|qu)y$", "${1}ies"}, - {"(x|ch|ss|sh)$", "${1}es"}, - {"(matr|vert|ind)(?:ix|ex)$", "${1}ices"}, - {"^(m|l)ouse$", "${1}ice"}, - {"^(m|l)ice$", "${1}ice"}, - {"^(ox)$", "${1}en"}, - {"^(oxen)$", "${1}"}, - {"(quiz)$", "${1}zes"}, -} - -var singularInflections = RegularSlice{ - {"s$", ""}, - {"(ss)$", "${1}"}, - {"(n)ews$", "${1}ews"}, - {"([ti])a$", "${1}um"}, - {"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$", "${1}sis"}, - {"(^analy)(sis|ses)$", "${1}sis"}, - {"([^f])ves$", "${1}fe"}, - {"(hive)s$", "${1}"}, - {"(tive)s$", "${1}"}, - {"([lr])ves$", "${1}f"}, - {"([^aeiouy]|qu)ies$", "${1}y"}, - {"(s)eries$", "${1}eries"}, - {"(m)ovies$", "${1}ovie"}, - {"(c)ookies$", "${1}ookie"}, - {"(x|ch|ss|sh)es$", "${1}"}, - {"^(m|l)ice$", "${1}ouse"}, - {"(bus)(es)?$", "${1}"}, - {"(o)es$", "${1}"}, - {"(shoe)s$", "${1}"}, - {"(cris|test)(is|es)$", "${1}is"}, - {"^(a)x[ie]s$", "${1}xis"}, - {"(octop|vir)(us|i)$", "${1}us"}, - {"(alias|status)(es)?$", "${1}"}, - {"^(ox)en", "${1}"}, - {"(vert|ind)ices$", "${1}ex"}, - {"(matr)ices$", "${1}ix"}, - {"(quiz)zes$", "${1}"}, - {"(database)s$", "${1}"}, -} - -var irregularInflections = IrregularSlice{ - {"person", "people"}, - {"man", "men"}, - {"child", "children"}, - {"sex", "sexes"}, - {"move", "moves"}, - {"mombie", "mombies"}, - {"criterion", "criteria"}, -} - -var uncountableInflections = []string{"equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "jeans", "police"} - -var compiledPlurals []inflection -var compiledSingles []inflection - -func init() { - - compiledPlurals = []inflection{} - compiledSingles = []inflection{} - - for _, uncountable := range uncountableInflections { - inf := inflection{ - regexp: regexp.MustCompile("^(?i)(" + uncountable + ")$"), - replace: "${1}", - } - compiledPlurals = append(compiledPlurals, inf) - compiledSingles = append(compiledSingles, inf) - } - - for _, value := range irregularInflections { - infs := []inflection{ - {regexp: regexp.MustCompile(strings.ToUpper(value.singular) + "$"), replace: strings.ToUpper(value.plural)}, - {regexp: regexp.MustCompile(strings.Title(value.singular) + "$"), replace: strings.Title(value.plural)}, - {regexp: regexp.MustCompile(value.singular + "$"), replace: value.plural}, - } - compiledPlurals = append(compiledPlurals, infs...) - } - - for _, value := range irregularInflections { - infs := []inflection{ - {regexp: regexp.MustCompile(strings.ToUpper(value.plural) + "$"), replace: strings.ToUpper(value.singular)}, - {regexp: regexp.MustCompile(strings.Title(value.plural) + "$"), replace: strings.Title(value.singular)}, - {regexp: regexp.MustCompile(value.plural + "$"), replace: value.singular}, - } - compiledSingles = append(compiledSingles, infs...) - } - - for i := len(pluralInflections) - 1; i >= 0; i-- { - value := pluralInflections[i] - infs := []inflection{ - {regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)}, - {regexp: regexp.MustCompile(value.find), replace: value.replace}, - {regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace}, - } - compiledPlurals = append(compiledPlurals, infs...) - } - - for i := len(singularInflections) - 1; i >= 0; i-- { - value := singularInflections[i] - infs := []inflection{ - {regexp: regexp.MustCompile(strings.ToUpper(value.find)), replace: strings.ToUpper(value.replace)}, - {regexp: regexp.MustCompile(value.find), replace: value.replace}, - {regexp: regexp.MustCompile("(?i)" + value.find), replace: value.replace}, - } - compiledSingles = append(compiledSingles, infs...) - } - -} - -// Plural converts a word to its plural form -func Pluralize(str string) string { - for _, inflection := range compiledPlurals { - if inflection.regexp.MatchString(str) { - return inflection.regexp.ReplaceAllString(str, inflection.replace) - } - } - return str -} - -// Singular converts a word to its singular form -func Singularize(str string) string { - for _, inflection := range compiledSingles { - if inflection.regexp.MatchString(str) { - return inflection.regexp.ReplaceAllString(str, inflection.replace) - } - } - return str -} diff --git a/util/lang/lang_test.go b/util/lang/lang_test.go deleted file mode 100644 index aeed1696..00000000 --- a/util/lang/lang_test.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package lang - -import ( - "strings" - "testing" -) - -var inflections = map[string]string{ - "star": "stars", - "STAR": "STARS", - "Star": "Stars", - "bus": "buses", - "fish": "fish", - "mouse": "mice", - "query": "queries", - "ability": "abilities", - "agency": "agencies", - "movie": "movies", - "archive": "archives", - "index": "indices", - "wife": "wives", - "safe": "saves", - "half": "halves", - "move": "moves", - "salesperson": "salespeople", - "person": "people", - "spokesman": "spokesmen", - "man": "men", - "woman": "women", - "basis": "bases", - "diagnosis": "diagnoses", - "diagnosis_a": "diagnosis_as", - "datum": "data", - "medium": "media", - "stadium": "stadia", - "analysis": "analyses", - "node_child": "node_children", - "child": "children", - "experience": "experiences", - "day": "days", - "comment": "comments", - "foobar": "foobars", - "newsletter": "newsletters", - "old_news": "old_news", - "news": "news", - "series": "series", - "species": "species", - "quiz": "quizzes", - "perspective": "perspectives", - "ox": "oxen", - "photo": "photos", - "buffalo": "buffaloes", - "tomato": "tomatoes", - "dwarf": "dwarves", - "elf": "elves", - "information": "information", - "equipment": "equipment", - "criterion": "criteria", -} - -// storage is used to restore the state of the global variables -// on each test execution, to ensure no global state pollution -type storage struct { - singulars RegularSlice - plurals RegularSlice - irregulars IrregularSlice - uncountables []string -} - -var backup = storage{} - -func TestPluralize(t *testing.T) { - for key, value := range inflections { - if v := Pluralize(strings.ToUpper(key)); v != strings.ToUpper(value) { - t.Errorf("%v's plural should be %v, but got %v", strings.ToUpper(key), strings.ToUpper(value), v) - } - - if v := Pluralize(strings.Title(key)); v != strings.Title(value) { - t.Errorf("%v's plural should be %v, but got %v", strings.Title(key), strings.Title(value), v) - } - - if v := Pluralize(key); v != value { - t.Errorf("%v's plural should be %v, but got %v", key, value, v) - } - } -} - -func TestSingularize(t *testing.T) { - for key, value := range inflections { - if v := Singularize(strings.ToUpper(value)); v != strings.ToUpper(key) { - t.Errorf("%v's singular should be %v, but got %v", strings.ToUpper(value), strings.ToUpper(key), v) - } - - if v := Singularize(strings.Title(value)); v != strings.Title(key) { - t.Errorf("%v's singular should be %v, but got %v", strings.Title(value), strings.Title(key), v) - } - - if v := Singularize(value); v != key { - t.Errorf("%v's singular should be %v, but got %v", value, key, v) - } - } -} diff --git a/util/math/abs.go b/util/math/abs.go deleted file mode 100644 index 7d5fa31e..00000000 --- a/util/math/abs.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Abs(val float64) float64 { - return math.Abs(val) -} diff --git a/util/math/bool.go b/util/math/bool.go deleted file mode 100644 index 757c7831..00000000 --- a/util/math/bool.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -func Bool(val bool) int { - if val { - return 1 - } - return 0 -} diff --git a/util/math/bottom.go b/util/math/bottom.go deleted file mode 100644 index ef7d0e76..00000000 --- a/util/math/bottom.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -func Bottom(vals []float64, take int) []float64 { - - var out []float64 - - if len(vals) == 0 { - return nil - } - - sort := Sort(vals) - - for i := 0; i < take && i < len(vals); i++ { - out = append(out, sort[i]) - } - - return out -} diff --git a/util/math/ceil.go b/util/math/ceil.go deleted file mode 100644 index 0f0a55ab..00000000 --- a/util/math/ceil.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Ceil(val float64) float64 { - return math.Ceil(val) -} diff --git a/util/math/copy.go b/util/math/copy.go deleted file mode 100644 index a791106e..00000000 --- a/util/math/copy.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -func Copy(vals []float64) []float64 { - - outs := make([]float64, len(vals)) - - copy(outs, vals) - - return outs - -} diff --git a/util/math/correlation.go b/util/math/correlation.go deleted file mode 100644 index b7ff3613..00000000 --- a/util/math/correlation.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Correlation(a, b []float64) float64 { - - if len(a) == 0 { - return math.NaN() - } - - if len(b) == 0 { - return math.NaN() - } - - if len(a) != len(b) { - return math.NaN() - } - - sa := PopulationStandardDeviation(a) - sb := PopulationStandardDeviation(b) - co := PopulationCovariance(a, b) - - if sa == 0 || sb == 0 { - return 0 - } - - return co / (sa * sb) - -} diff --git a/util/math/covariance.go b/util/math/covariance.go deleted file mode 100644 index b610a51a..00000000 --- a/util/math/covariance.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Covariance(a, b []float64) float64 { - - var ss float64 - - if len(a) == 0 { - return math.NaN() - } - - if len(b) == 0 { - return math.NaN() - } - - if len(a) != len(b) { - return math.NaN() - } - - l, ma, mb := Size(a), Mean(a), Mean(b) - - for i := 0; i < l; i++ { - da := (a[i] - ma) - db := (b[i] - mb) - ss += (da*db - ss) / float64(i+1) - } - - return ss * float64(l) / float64(l-1) - -} - -func PopulationCovariance(a, b []float64) float64 { - - var ss float64 - - if len(a) == 0 { - return math.NaN() - } - - if len(b) == 0 { - return math.NaN() - } - - if len(a) != len(b) { - return math.NaN() - } - - l, ma, mb := Size(a), Mean(a), Mean(b) - - for i := 0; i < l; i++ { - da := (a[i] - ma) - db := (b[i] - mb) - ss += da * db - } - - return ss / float64(l) - -} diff --git a/util/math/deviation.go b/util/math/deviation.go deleted file mode 100644 index 0f9a5135..00000000 --- a/util/math/deviation.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func StandardDeviation(vals []float64, sample bool) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return math.Pow(Variance(vals, sample), 0.5) - -} - -func SampleStandardDeviation(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return math.Pow(SampleVariance(vals), 0.5) - -} - -func PopulationStandardDeviation(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return math.Pow(PopulationVariance(vals), 0.5) - -} diff --git a/util/math/floor.go b/util/math/floor.go deleted file mode 100644 index 2aaf5888..00000000 --- a/util/math/floor.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Floor(val float64) float64 { - return math.Floor(val) -} diff --git a/util/math/max.go b/util/math/max.go deleted file mode 100644 index d8eb960b..00000000 --- a/util/math/max.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Max(vals []float64) float64 { - - var max float64 - - if len(vals) == 0 { - return math.NaN() - } - - max = vals[0] - - for _, v := range vals { - if v > max { - max = v - } - } - - return max - -} diff --git a/util/math/mean.go b/util/math/mean.go deleted file mode 100644 index 88dc8225..00000000 --- a/util/math/mean.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Mean(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return Sum(vals) / float64(len(vals)) - -} - -func RollingMean(cnt int64, sum float64) float64 { - - return sum / float64(cnt) - -} - -func GeometricMean(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return math.Pow(Product(vals), 1/float64(len(vals))) - -} - -func HarmonicMean(vals []float64) float64 { - - var out float64 - - if len(vals) == 0 { - return math.NaN() - } - - for _, v := range vals { - if v < 0 { - return math.NaN() - } else if v == 0 { - return math.NaN() - } - out += (1 / v) - } - - return float64(len(vals)) / out - -} diff --git a/util/math/median.go b/util/math/median.go deleted file mode 100644 index ff7dca46..00000000 --- a/util/math/median.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Median(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - l := len(vals) - - switch { - case l%2 == 0: - sort := Sort(vals) - return Mean(sort[l/2-1 : l/2+1]) - default: - sort := Sort(vals) - return float64(sort[l/2]) - } - -} - -func MedianAbsoluteDeviation(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - dups := Copy(vals) - - m := Median(dups) - - for k, v := range dups { - dups[k] = math.Abs(v - m) - } - - return Median(dups) - -} diff --git a/util/math/midhinge.go b/util/math/midhinge.go deleted file mode 100644 index 7bc5f075..00000000 --- a/util/math/midhinge.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Midhinge(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - q1, _, q3 := Quartile(vals) - - return (q1 + q3) / 2 - -} diff --git a/util/math/min.go b/util/math/min.go deleted file mode 100644 index 48ebfb72..00000000 --- a/util/math/min.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Min(vals []float64) float64 { - - var min float64 - - if len(vals) == 0 { - return math.NaN() - } - - min = vals[0] - - for _, v := range vals { - if v < min { - min = v - } - } - - return min - -} diff --git a/util/math/mode.go b/util/math/mode.go deleted file mode 100644 index de896c6e..00000000 --- a/util/math/mode.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "sort" - -func Mode(vals []float64) []float64 { - - var out []float64 - - switch len(vals) { - case 1: - return vals - case 0: - return nil - } - - if !sort.Float64sAreSorted(vals) { - vals = Sort(vals) - } - - out = make([]float64, 5) - - cnt, max := 1, 1 - - for i := 1; i < len(vals); i++ { - switch { - case vals[i] == vals[i-1]: - cnt++ - case cnt == max && max != 1: - out = append(out, vals[i-1]) - cnt = 1 - case cnt > max: - out = append(out[:0], vals[i-1]) - max, cnt = cnt, 1 - default: - cnt = 1 - } - } - - switch { - case cnt == max: - out = append(out, vals[len(vals)-1]) - case cnt > max: - out = append(out[:0], vals[len(vals)-1]) - max = cnt - } - - if max == 1 { - return nil - } - - return out -} diff --git a/util/math/percentile.go b/util/math/percentile.go deleted file mode 100644 index 0deebbef..00000000 --- a/util/math/percentile.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Percentile(vals []float64, percent float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - if percent <= 0 || percent > 100 { - return math.NaN() - } - - sort := Sort(vals) - size := Size(vals) - indx := (percent / 100) * float64(size) - - switch { - case indx == Whole(indx): - i := int(indx) - return sort[i-1] - case indx > 1: - i := int(indx) - return Mean([]float64{sort[i-1], sort[i]}) - default: - return math.NaN() - } - -} - -func NearestRankPercentile(vals []float64, percent float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - if percent <= 0 || percent > 100 { - return math.NaN() - } - - sort := Sort(vals) - size := Size(vals) - - if percent == 100 { - return sort[size-1] - } - - r := int(math.Ceil(float64(size) * percent / 100)) - - if r == 0 { - return sort[0] - } - - return sort[r-1] - -} diff --git a/util/math/product.go b/util/math/product.go deleted file mode 100644 index 0a1283bd..00000000 --- a/util/math/product.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Product(vals []float64) float64 { - - var out float64 - - if len(vals) == 0 { - return math.NaN() - } - - for _, v := range vals { - switch out { - case 0: - out = v - default: - out *= v - } - } - - return out - -} diff --git a/util/math/quartile.go b/util/math/quartile.go deleted file mode 100644 index a753e6b0..00000000 --- a/util/math/quartile.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Quartile(vals []float64) (float64, float64, float64) { - - if len(vals) == 0 { - return math.NaN(), math.NaN(), math.NaN() - } - - l := len(vals) - - switch { - case l%2 == 0: - c1 := l / 2 - c2 := l / 2 - sort := Sort(vals) - return Median(sort[:c1]), Median(sort), Median(sort[c2:]) - default: - c1 := (l - 1) / 2 - c2 := c1 + 1 - sort := Sort(vals) - return Median(sort[:c1]), Median(sort), Median(sort[c2:]) - } - -} - -func InterQuartileRange(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - q1, _, q3 := Quartile(vals) - - return q3 - q1 - -} diff --git a/util/math/round.go b/util/math/round.go deleted file mode 100644 index 277f7ff8..00000000 --- a/util/math/round.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Round(val float64) float64 { - return math.Floor(val + 0.5) -} diff --git a/util/math/sample.go b/util/math/sample.go deleted file mode 100644 index 521250cb..00000000 --- a/util/math/sample.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math/rand" - -func Sample(vals []float64, take int) []float64 { - - var out []float64 - - if len(vals) == 0 { - return nil - } - - for k, v := range rand.Perm(len(vals)) { - if k < take { - out = append(out, vals[v]) - continue - } - break - } - - return out - -} diff --git a/util/math/size.go b/util/math/size.go deleted file mode 100644 index a5fdab45..00000000 --- a/util/math/size.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -func Size(vals []float64) int { - return len(vals) -} diff --git a/util/math/sort.go b/util/math/sort.go deleted file mode 100644 index 2682aacc..00000000 --- a/util/math/sort.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "sort" - -func Sort(vals []float64) []float64 { - - outs := Copy(vals) - - sort.Float64s(outs) - - return outs - -} diff --git a/util/math/spread.go b/util/math/spread.go deleted file mode 100644 index 596370af..00000000 --- a/util/math/spread.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Spread(vals []float64) float64 { - - var min, max float64 - - switch len(vals) { - case 0: - return math.NaN() - case 1: - return 0 - } - - for _, v := range vals { - switch { - case v < min: - min = v - case v > max: - max = v - } - } - - return (max - min) - 1 - -} diff --git a/util/math/sqrt.go b/util/math/sqrt.go deleted file mode 100644 index 7bb593bf..00000000 --- a/util/math/sqrt.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Sqrt(val float64) float64 { - return math.Sqrt(val) -} diff --git a/util/math/sum.go b/util/math/sum.go deleted file mode 100644 index 6c5333c7..00000000 --- a/util/math/sum.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Sum(vals []float64) float64 { - - var sum float64 - - if len(vals) == 0 { - return math.NaN() - } - - for _, v := range vals { - sum += v - } - - return sum - -} diff --git a/util/math/top.go b/util/math/top.go deleted file mode 100644 index a0d9c975..00000000 --- a/util/math/top.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -func Top(vals []float64, take int) []float64 { - - var out []float64 - - if len(vals) == 0 { - return nil - } - - sort := Sort(vals) - - for i := 0; i < take && i < len(vals); i++ { - out = append(out, sort[len(vals)-1-i]) - } - - return out -} diff --git a/util/math/trimean.go b/util/math/trimean.go deleted file mode 100644 index 826071a4..00000000 --- a/util/math/trimean.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Trimean(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - q1, q2, q3 := Quartile(vals) - - return (q1 + (q2 * 2) + q3) / 4 - -} diff --git a/util/math/variance.go b/util/math/variance.go deleted file mode 100644 index 03c800cd..00000000 --- a/util/math/variance.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -import "math" - -func Variance(vals []float64, sample bool) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - var out float64 - - m := Mean(vals) - - for _, v := range vals { - out += (float64(v) - m) * (float64(v) - m) - } - - return out / float64((len(vals) - (1 * Bool(sample)))) - -} - -func SampleVariance(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return Variance(vals, true) - -} - -func PopulationVariance(vals []float64) float64 { - - if len(vals) == 0 { - return math.NaN() - } - - return Variance(vals, false) - -} diff --git a/util/math/whole.go b/util/math/whole.go deleted file mode 100644 index 2bd7291f..00000000 --- a/util/math/whole.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package math - -func Whole(val float64) float64 { - return float64(int64(val)) -} diff --git a/util/nums/nums.go b/util/nums/nums.go deleted file mode 100644 index c8db6ea1..00000000 --- a/util/nums/nums.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package nums - -import ( - "fmt" - "strconv" - "strings" -) - -func CountPlaces(v float64) int { - - s := strconv.FormatFloat(v, 'f', -1, 64) - i := strings.IndexByte(s, '.') - - if i > -1 { - return len(s) - i - 1 - } - - return 0 - -} - -func FormatPlaces(v float64, p int) float64 { - - switch p { - case 0: - return float64(int(v)) - case 1: - f := fmt.Sprintf("%.1f", v) - o, _ := strconv.ParseFloat(f, 64) - return o - case 2: - f := fmt.Sprintf("%.2f", v) - o, _ := strconv.ParseFloat(f, 64) - return o - case 3: - f := fmt.Sprintf("%.3f", v) - o, _ := strconv.ParseFloat(f, 64) - return o - case 4: - f := fmt.Sprintf("%.4f", v) - o, _ := strconv.ParseFloat(f, 64) - return o - default: - f := fmt.Sprintf("%.5f", v) - o, _ := strconv.ParseFloat(f, 64) - return o - } - -} diff --git a/util/pack/pack.go b/util/pack/pack.go deleted file mode 100644 index 0ff5556d..00000000 --- a/util/pack/pack.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pack - -import ( - "github.com/surrealdb/cork" -) - -var opt = cork.Handle{ - SortMaps: true, - ArrType: make([]interface{}, 0), - MapType: make(map[string]interface{}), -} - -// Encode encodes a data object into a CORK. -func Encode(src interface{}) (dst []byte) { - enc := cork.NewEncoderBytesFromPool(&dst) - enc.Options(&opt) - err := enc.Encode(src) - enc.Reset() - if err != nil { - panic(err) - } - return -} - -// Decode decodes a CORK into a data object. -func Decode(src []byte, dst interface{}) { - dec := cork.NewDecoderBytesFromPool(src) - dec.Options(&opt) - err := dec.Decode(dst) - dec.Reset() - if err != nil { - panic(err) - } - return -} diff --git a/util/rand/ints.go b/util/rand/ints.go deleted file mode 100644 index 4936f40c..00000000 --- a/util/rand/ints.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rand - -import ( - "time" - - "math/rand" -) - -func init() { - rand.Seed(time.Now().UTC().UnixNano()) -} - -func Int() int { - return rand.Int() -} - -func Int64() int64 { - return rand.Int63() -} - -func Float64() float64 { - return rand.Float64() -} diff --git a/util/rand/rand.go b/util/rand/rand.go deleted file mode 100644 index 0d6ad243..00000000 --- a/util/rand/rand.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rand - -import ( - "crypto/rand" -) - -var chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") - -// New produces a random string of length n -func New(l int) []byte { - - if l == 0 { - return nil - } - - i := 0 - t := len(chars) - m := 255 - (256 % t) - b := make([]byte, l) - r := make([]byte, l+(l/4)) - - for { - - rand.Read(r) - - for _, rb := range r { - c := int(rb) - if c > m { - continue - } - b[i] = chars[c%t] - i++ - if i == l { - return b - } - } - - } - -} diff --git a/util/rand/rand_test.go b/util/rand/rand_test.go deleted file mode 100644 index 32c742b9..00000000 --- a/util/rand/rand_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rand - -import ( - "fmt" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestNew(t *testing.T) { - - for i := 0; i < 100; i++ { - - Convey(fmt.Sprintf("Random string of length %d", i), t, func() { - Convey("Should be of correct length", func() { - So(New(i), ShouldHaveLength, i) - }) - }) - - } - -} diff --git a/util/rand/strings.go b/util/rand/strings.go deleted file mode 100644 index 7eebdc11..00000000 --- a/util/rand/strings.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package rand - -func String(l int) string { - return string(New(l)) -} diff --git a/util/show/show.go b/util/show/show.go deleted file mode 100644 index 4859f8da..00000000 --- a/util/show/show.go +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package show - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/data" - "github.com/surrealdb/surrealdb/util/lang" -) - -type Display int8 - -const ( - One Display = iota - Many -) - -type Method int8 - -const ( - Select Method = iota - Create - Update - Delete - Modify - Trace -) - -func Output(c *fibre.Context, t string, d Display, m Method, res []*db.Response, err error) error { - - switch err.(type) { - case *sql.ParseError: - return fibre.NewHTTPError(400) // Will happen if invalid json - case *db.BlankError: - return fibre.NewHTTPError(403) // Will happen if invalid auth - case *db.PermsError: - return fibre.NewHTTPError(403) // Will happen if invalid auth - case *fibre.HTTPError: - return err // Probably a timeout error - } - - if len(res) == 0 { - return fibre.NewHTTPError(500) // Should not happen - } - - switch c.Type() { - case "application/json": - return OutputRest(c, t, d, m, res, err) - case "application/cbor": - return OutputRest(c, t, d, m, res, err) - case "application/msgpack": - return OutputRest(c, t, d, m, res, err) - case "application/vnd.api+json": - return OutputJson(c, t, d, m, res, err) - } - - return nil - -} - -// -------------------------------------------------- -// Endpoints for manipulating multiple records -// -------------------------------------------------- - -// OutputBase outputs the response data directly from the SQL -// query reponse without any manipulation or alteration. -func OutputBase(c *fibre.Context, t string, d Display, m Method, res []*db.Response, err error) error { - - var ret *db.Response - - switch ret = res[0]; ret.Status { - case "OK": - return c.Send(200, ret) - case "ERR_DB": - return fibre.NewHTTPError(503) - case "ERR_KV": - return fibre.NewHTTPError(409, ret.Detail) - case "ERR_PE": - return fibre.NewHTTPError(403, ret.Detail) - case "ERR_FD": - return fibre.NewHTTPError(422, ret.Detail) - case "ERR_IX": - return fibre.NewHTTPError(422, ret.Detail) - case "ERR_TO": - return fibre.NewHTTPError(504, ret.Detail) - default: - return fibre.NewHTTPError(400, ret.Detail) - } - -} - -// OutputRest outputs the json response data according to the specification -// available at http://emberjs.com/api/data/classes/DS.RESTAdapter.html and -// according to http://stackoverflow.com/questions/14922623. -func OutputRest(c *fibre.Context, t string, d Display, m Method, res []*db.Response, err error) error { - - var ret *db.Response - - switch ret = res[0]; ret.Status { - case "OK": - break - case "ERR_DB": - return fibre.NewHTTPError(503) - case "ERR_KV": - return fibre.NewHTTPError(409, ret.Detail) - case "ERR_PE": - return fibre.NewHTTPError(403, ret.Detail) - case "ERR_FD": - return fibre.NewHTTPError(422, ret.Detail) - case "ERR_IX": - return fibre.NewHTTPError(422, ret.Detail) - case "ERR_TO": - return fibre.NewHTTPError(504, ret.Detail) - default: - return fibre.NewHTTPError(400, ret.Detail) - } - - if len(res[0].Result) == 0 { - return c.Send(204, nil) - } - - switch m { - case Delete: - return c.Send(204, nil) - case Create: - return c.Send(201, map[string]interface{}{ - lang.Singularize(t): cleanRestOne(res[0].Result[0]), - }) - } - - switch d { - case One: - return c.Send(200, map[string]interface{}{ - lang.Singularize(t): cleanRestOne(res[0].Result[0]), - }) - case Many: - return c.Send(200, map[string]interface{}{ - lang.Pluralize(t): cleanRestAll(res[0].Result), - }) - } - - return c.Send(200, nil) - -} - -func cleanRestAll(vals []interface{}) (all []*data.Doc) { - - for _, val := range vals { - all = append(all, cleanRestOne(val)) - } - - return - -} - -func cleanRestOne(val interface{}) (one *data.Doc) { - - one = data.Consume(val) - one.Iff(one.Get("meta.id").Data(), "id") - - return - -} - -// OutputJson outputs the json response data according to the specification -// available at http://jsonapi.org/format/. Currently linked data does not -// adhere to the specification, but is intead displayed inside the attribute -// object. Links and embedded paths are also not implemented. -func OutputJson(c *fibre.Context, t string, d Display, m Method, res []*db.Response, err error) error { - - var ret *db.Response - - switch ret = res[0]; ret.Status { - case "OK": - break - case "ERR_DB": - return fibre.NewHTTPError(503) - case "ERR_KV": - return fibre.NewHTTPError(409, ret.Detail) - case "ERR_PE": - return fibre.NewHTTPError(403, ret.Detail) - case "ERR_FD": - return fibre.NewHTTPError(422, ret.Detail) - case "ERR_IX": - return fibre.NewHTTPError(422, ret.Detail) - case "ERR_TO": - return fibre.NewHTTPError(504, ret.Detail) - default: - return fibre.NewHTTPError(400, ret.Detail) - } - - if len(res[0].Result) == 0 { - return c.Send(204, nil) - } - - switch m { - case Delete: - return c.Send(204, nil) - case Create: - return c.Send(201, map[string]interface{}{ - "data": cleanJsonOne(res[0].Result[0]), - }) - } - - switch d { - case One: - return c.Send(200, map[string]interface{}{ - "data": cleanJsonOne(res[0].Result[0]), - }) - case Many: - return c.Send(200, map[string]interface{}{ - "data": cleanJsonAll(res[0].Result), - }) - } - - return c.Send(200, nil) - -} - -func cleanJsonAll(vals []interface{}) (all []*data.Doc) { - - for _, val := range vals { - all = append(all, cleanJsonOne(val)) - } - - return - -} - -func cleanJsonOne(val interface{}) (one *data.Doc) { - - one = data.New() - old := data.Consume(val) - one.Set(old.Get("meta.id").Data(), "id") - one.Set(old.Get("meta.tb").Data(), "type") - one.Set(old.Data(), "attributes") - one.Del("attributes.id") - one.Del("attributes.meta") - - return - -} diff --git a/util/slug/lang.go b/util/slug/lang.go deleted file mode 100644 index bbd49401..00000000 --- a/util/slug/lang.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package slug - -func init() { - // Merge language subs with the default one - for _, sub := range []*map[rune]string{&en, &de, &fr, &es, &nl, &pl, &gr} { - for key, value := range defaults { - (*sub)[key] = value - } - } -} - -var defaults = map[rune]string{ - '"': "", - '\'': "", - '’': "", - '‒': "-", // figure dash - '–': "-", // en dash - '—': "-", // em dash - '―': "-", // horizontal bar -} - -var en = map[rune]string{ - '&': "and", - '@': "at", -} - -var de = map[rune]string{ - '&': "und", - '@': "an", -} - -var fr = map[rune]string{ - '&': "et", - '@': "a", -} - -var es = map[rune]string{ - '&': "y", - '@': "en", -} - -var nl = map[rune]string{ - '&': "en", - '@': "at", -} - -var pl = map[rune]string{ - '&': "i", - '@': "na", -} - -var gr = map[rune]string{ - '&': "kai", - 'η': "i", - 'ή': "i", - 'Η': "i", - 'ι': "i", - 'ί': "i", - 'Ι': "i", - 'χ': "x", - 'Χ': "x", -} diff --git a/util/slug/slug.go b/util/slug/slug.go deleted file mode 100644 index 7ea6d1bd..00000000 --- a/util/slug/slug.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package slug - -import ( - "bytes" - "regexp" - "strings" - - "github.com/rainycape/unidecode" -) - -var ( - regexpUnicode = regexp.MustCompile("[^a-z0-9-_]") - regexpHyphens = regexp.MustCompile("-+") -) - -func Make(s string) (slug string) { - return MakeLang(s, "en") -} - -func MakeLang(s string, l string) (slug string) { - - slug = strings.TrimSpace(s) - - switch l { - case "de": - slug = substitute(slug, de) - case "en": - slug = substitute(slug, en) - case "pl": - slug = substitute(slug, pl) - case "es": - slug = substitute(slug, es) - case "gr": - slug = substitute(slug, gr) - case "nl": - slug = substitute(slug, nl) - default: - slug = substitute(slug, en) - } - - // Process all non ASCII symbols - slug = unidecode.Unidecode(slug) - - // Format the text as lower case - slug = strings.ToLower(slug) - - // Process remaining symbols - slug = regexpUnicode.ReplaceAllString(slug, "-") - - // Process duplicated hyphens - slug = regexpHyphens.ReplaceAllString(slug, "-") - - // Trim leading hyphens - slug = strings.Trim(slug, "-") - - return slug - -} - -func substitute(s string, sub map[rune]string) string { - var buf bytes.Buffer - for _, c := range s { - if d, ok := sub[c]; ok { - buf.WriteString(d) - } else { - buf.WriteRune(c) - } - } - return buf.String() -} diff --git a/util/text/text.go b/util/text/text.go deleted file mode 100644 index d4ccf254..00000000 --- a/util/text/text.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package text - -func Levenshtein(one, two string) int { - - var cost, olddiag, lastdiag int - - s1 := []rune(one) - s2 := []rune(two) - - l1 := len(s1) - l2 := len(s2) - - column := make([]int, l1+1) - - for y := 1; y <= l1; y++ { - column[y] = y - } - - for x := 1; x <= l2; x++ { - column[0] = x - lastdiag = x - 1 - for y := 1; y <= l1; y++ { - olddiag = column[y] - cost = 0 - if s1[y-1] != s2[x-1] { - cost = 1 - } - column[y] = min( - column[y]+1, - column[y-1]+1, - lastdiag+cost, - ) - lastdiag = olddiag - } - } - - return column[l1] - -} - -func min(a, b, c int) int { - if a < b { - if a < c { - return a - } - } else { - if b < c { - return b - } - } - return c -} diff --git a/util/uuid/uuid.go b/util/uuid/uuid.go deleted file mode 100644 index 6565b77e..00000000 --- a/util/uuid/uuid.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package uuid - -import ( - "github.com/satori/go.uuid" -) - -var ( - NamespaceDNS = uuid.NamespaceDNS - NamespaceURL = uuid.NamespaceURL - NamespaceOID = uuid.NamespaceOID - NamespaceX500 = uuid.NamespaceX500 -) - -type UUID struct { - uuid.UUID -} - -// New returns a new UUID (Version 4) using 16 random bytes or panics. -func New() *UUID { - return &UUID{uuid.NewV4()} -} - -// Parse parses and checks for a valid UUID string, and returns nil if not valid. -func Parse(input string) *UUID { - id, err := uuid.FromString(input) - if err != nil { - return nil - } - return &UUID{id} -} diff --git a/util/uuid/uuid_test.go b/util/uuid/uuid_test.go deleted file mode 100644 index e146cce8..00000000 --- a/util/uuid/uuid_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package uuid - -import ( - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func TestNew(t *testing.T) { - - var str *UUID - - str = New() - - Convey(str.String(), t, func() { - Convey("Should be a UUID", func() { - So(str, ShouldHaveSameTypeAs, &UUID{}) - }) - Convey("Should not be nil", func() { - So(str, ShouldNotBeNil) - }) - Convey("Should be of length 36", func() { - So(str.String(), ShouldHaveLength, 36) - }) - }) - -} - -func TestParsing(t *testing.T) { - - var str *UUID - - str = Parse("thiswill-notbe-parsed-as-successful") - - Convey("Parse thiswill-notbe-parsed-as-successful", t, func() { - Convey("Should be nil", func() { - So(str, ShouldBeNil) - }) - }) - - str = Parse("1400A118-2749-4605-833C-E7437488BCBF") - - Convey("Parse 1400A118-2749-4605-833C-E7437488BCBF", t, func() { - Convey("Should be a UUID", func() { - So(str, ShouldHaveSameTypeAs, &UUID{}) - }) - Convey("Should not be nil", func() { - So(str, ShouldNotBeNil) - }) - Convey("Should be of length 36", func() { - So(str.String(), ShouldHaveLength, 36) - }) - Convey("Should be exactly `1400a118-2749-4605-833c-e7437488bcbf`", func() { - So(str.String(), ShouldEqual, "1400a118-2749-4605-833c-e7437488bcbf") - }) - }) - -} diff --git a/web/auth.go b/web/auth.go deleted file mode 100644 index 2301cb7a..00000000 --- a/web/auth.go +++ /dev/null @@ -1,448 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "fmt" - "net" - - "bytes" - "strings" - - "encoding/base64" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" - "github.com/dgrijalva/jwt-go" - "github.com/gorilla/websocket" -) - -var ignore = func() error { - return nil -} - -func cidr(ip net.IP, networks []*net.IPNet) bool { - for _, network := range networks { - if network.Contains(ip) { - return true - } - } - return false -} - -func auth() fibre.MiddlewareFunc { - return func(h fibre.HandlerFunc) fibre.HandlerFunc { - return func(c *fibre.Context) (err error) { - - // Initialise the connection authentication - // information which will store whether the - // connection has authenticated or not. - - auth := new(cnf.Auth) - c.Set(varKeyAuth, auth) - - // Start off with an authentication level - // which prevents running any sql queries, - // and denies access to all data. - - auth.Kind = cnf.AuthNO - - // Retrieve the current domain host and - // if we are using a subdomain then set - // the NS and DB to the subdomain bits. - - bits := strings.Split(c.Request().URL().Host, ".") - subs := strings.Split(bits[0], "-") - - if len(subs) == 2 { - auth.NS = subs[0] - auth.DB = subs[1] - } - - // If there is a Session ID specified in - // the request headers, then mark it as - // the connection Session ID. - - if id := c.Request().Header().Get(varKeyId); len(id) != 0 { - c.Set(varKeyUniq, id) - } - - // If there is a namespace specified in - // the request headers, then mark it as - // the selected namespace. - - if ns := c.Request().Header().Get(varKeyNs); len(ns) != 0 { - auth.NS = ns - } - - // If there is a database specified in - // the request headers, then mark it as - // the selected database. - - if db := c.Request().Header().Get(varKeyDb); len(db) != 0 { - auth.DB = db - } - - // Retrieve the HTTP Authorization header - // from the request, so that we can detect - // whether it is Basic auth or Bearer auth. - - head := c.Request().Header().Get("Authorization") - - // Check whether the Authorization header - // is a Basic Auth header, and if it is then - // process this as root authentication. - - if len(head) > 6 && head[:5] == "Basic" { - return checkBasics(c, head[6:], func() error { - return h(c) - }) - } - - // Check whether the Authorization header - // is a Bearer Auth header, and if it is then - // process this as default authentication. - - if len(head) > 7 && head[:6] == "Bearer" { - return checkBearer(c, head[7:], func() error { - return h(c) - }) - } - - // If there is no HTTP Authorization header, - // check to see if there are confuguration - // options specified in the socket protocols. - - if len(head) == 0 { - - // If there is a Session ID specified as - // one of the socket protocols then use - // this as the connection Session ID. - - for _, prot := range websocket.Subprotocols(c.Request().Request) { - if len(prot) > 3 && prot[0:3] == "id-" { - c.Set(varKeyUniq, prot[3:]) - } - } - - // If there is a NS configuration option - // defined as one of the socket protocols - // then use this as the selected NS. - - for _, prot := range websocket.Subprotocols(c.Request().Request) { - if len(prot) > 3 && prot[0:3] == "ns-" { - auth.NS = prot[3:] - } - } - - // If there is a DB configuration option - // defined as one of the socket protocols - // then use this as the selected DB. - - for _, prot := range websocket.Subprotocols(c.Request().Request) { - if len(prot) > 3 && prot[0:3] == "db-" { - auth.DB = prot[3:] - } - } - - // If there is a Auth configuration option - // defined as one of the socket protocols - // then use this as the auth information. - - for _, prot := range websocket.Subprotocols(c.Request().Request) { - if len(prot) > 5 && prot[0:5] == "auth-" { - if err := checkBasics(c, prot[5:], ignore); err == nil { - return h(c) - } - if err := checkBearer(c, prot[5:], ignore); err == nil { - return h(c) - } - } - } - - } - - return h(c) - - } - } -} - -func checkBasics(c *fibre.Context, info string, callback func() error) (err error) { - - var base []byte - var cred [][]byte - - auth := c.Get(varKeyAuth).(*cnf.Auth) - user := []byte(cnf.Settings.Auth.User) - pass := []byte(cnf.Settings.Auth.Pass) - - // Parse the base64 encoded basic auth data - - if base, err = base64.StdEncoding.DecodeString(info); err != nil { - return fibre.NewHTTPError(401).WithMessage("Problem with basic auth data") - } - - // Split the basic auth USER and PASS details - - if cred = bytes.SplitN(base, []byte(":"), 2); len(cred) != 2 { - return fibre.NewHTTPError(401).WithMessage("Problem with basic auth data") - } - - // Check to see if IP, USER, and PASS match server settings - - if bytes.Equal(cred[0], user) && bytes.Equal(cred[1], pass) { - - // FIXME does not work for IPv6 addresses - - if cidr(c.IP(), cnf.Settings.Auth.Nets) { - auth.Kind = cnf.AuthKV - return callback() - } - - return fibre.NewHTTPError(403).WithMessage("IP invalid for root authentication") - - } - - // If no KV authentication, then try to authenticate as NS user - - if auth.NS != "" { - - n := auth.NS - u := string(cred[0]) - p := string(cred[1]) - - if _, err = signinNS(c, n, u, p); err == nil { - auth.Kind = cnf.AuthNS - auth.NS = n - return callback() - } - - // If no NS authentication, then try to authenticate as DB user - - if auth.DB != "" { - - n := auth.NS - d := auth.DB - u := string(cred[0]) - p := string(cred[1]) - - if _, err = signinDB(c, n, d, u, p); err == nil { - auth.Kind = cnf.AuthDB - auth.NS = n - auth.DB = d - return callback() - } - - } - - } - - return fibre.NewHTTPError(401).WithMessage("Invalid authentication details") - -} - -func checkBearer(c *fibre.Context, info string, callback func() error) (err error) { - - var tx *txn.TX - var res []*db.Response - var vars jwt.MapClaims - var nsk, dbk, sck, tkk, usk, tbk, idk bool - var nsv, dbv, scv, tkv, usv, tbv, idv string - - // Start a new read transaction. - - if tx, err = txn.New(c.Context(), false); err != nil { - return fibre.NewHTTPError(500) - } - - // Ensure the transaction closes. - - defer tx.Cancel() - - // Get the current context. - - ctx := c.Context() - - // Reset the auth data first. - - auth := c.Get(varKeyAuth).(*cnf.Auth).Reset() - - // Parse the specified JWT Token. - - token, err := jwt.Parse(info, func(token *jwt.Token) (interface{}, error) { - - vars = token.Claims.(jwt.MapClaims) - - if err := vars.Valid(); err != nil { - return nil, err - } - - nsv, nsk = vars[varKeyNs].(string) // Namespace - dbv, dbk = vars[varKeyDb].(string) // Database - scv, sck = vars[varKeySc].(string) // Scope - tkv, tkk = vars[varKeyTk].(string) // Token - usv, usk = vars[varKeyUs].(string) // Login - tbv, tbk = vars[varKeyTb].(string) // Table - idv, idk = vars[varKeyId].(string) // Thing - - if tkv == "default" { - if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method") - } - } - - if nsk && dbk && sck && tkk { - - scp, err := tx.GetSC(ctx, nsv, dbv, scv) - if err != nil { - return nil, fmt.Errorf("Credentials failed") - } - - // Store the authenticated scope. - - auth.Scope = scp.Name.VA - - // Store the authenticated thing. - - if tbk && idk { - auth.Data = sql.NewThing(tbv, idv) - } - - // Check that the scope specifies connect. - - if exp, ok := scp.Connect.(*sql.SubExpression); ok { - - // Process the scope connect statement. - - c := fibre.NewContext(c.Request(), c.Response(), c.Fibre()) - - c.Set(varKeyAuth, &cnf.Auth{Kind: cnf.AuthDB, NS: nsv, DB: dbv}) - - qvars := map[string]interface{}{ - "id": auth.Data, "token": vars, - } - - query := &sql.Query{Statements: []sql.Statement{exp.Expr}} - - // If the query fails then fail authentication. - - if res, err = db.Process(c, query, qvars); err != nil { - return nil, fmt.Errorf("Credentials failed") - } - - // If the response is not 1 record then fail authentication. - - if len(res) != 1 || len(res[0].Result) != 1 { - return nil, fmt.Errorf("Credentials failed") - } - - auth.Data = res[0].Result[0] - - } - - if tkv != "default" { - key, err := tx.GetST(ctx, nsv, dbv, scv, tkv) - if err != nil { - return nil, fmt.Errorf("Credentials failed") - } - if token.Header["alg"] != key.Type { - return nil, fmt.Errorf("Unexpected signing method") - } - auth.Kind = cnf.AuthSC - return key.Code, nil - } else { - auth.Kind = cnf.AuthSC - return scp.Code, nil - } - - } else if nsk && dbk && tkk { - - if tkv != "default" { - key, err := tx.GetDT(ctx, nsv, dbv, tkv) - if err != nil { - return nil, fmt.Errorf("Credentials failed") - } - if token.Header["alg"] != key.Type { - return nil, fmt.Errorf("Unexpected signing method") - } - auth.Kind = cnf.AuthDB - return key.Code, nil - } else if usk { - usr, err := tx.GetDU(ctx, nsv, dbv, usv) - if err != nil { - return nil, fmt.Errorf("Credentials failed") - } - auth.Kind = cnf.AuthDB - return usr.Code, nil - } - - } else if nsk && tkk { - - if tkv != "default" { - key, err := tx.GetNT(ctx, nsv, tkv) - if err != nil { - return nil, fmt.Errorf("Credentials failed") - } - if token.Header["alg"] != key.Type { - return nil, fmt.Errorf("Unexpected signing method") - } - auth.Kind = cnf.AuthNS - return key.Code, nil - } else if usk { - usr, err := tx.GetNU(ctx, nsv, usv) - if err != nil { - return nil, fmt.Errorf("Credentials failed") - } - auth.Kind = cnf.AuthNS - return usr.Code, nil - } - - } - - return nil, fmt.Errorf("No available token") - - }) - - if err == nil && token.Valid { - - if auth.Kind == cnf.AuthNS { - auth.NS = nsv - } - - if auth.Kind == cnf.AuthDB { - auth.NS = nsv - auth.DB = dbv - } - - if auth.Kind == cnf.AuthSC { - auth.NS = nsv - auth.DB = dbv - } - - return callback() - - } else { - - auth.Reset() - - } - - return fibre.NewHTTPError(401).WithMessage("Invalid authentication details: " + err.Error()) - -} diff --git a/web/err.go b/web/err.go deleted file mode 100644 index a3dc133c..00000000 --- a/web/err.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/sql" -) - -func errors(val error, c *fibre.Context) { - - if c.IsSocket() { - return - } - - if c.IsComplete() { - return - } - - var code int - var info string - - switch e := val.(type) { - default: - code, info = 400, e.Error() - case *sql.ParseError: - code, info = 400, e.Error() - case *fibre.HTTPError: - code, info = e.Code(), e.Error() - } - - if _, ok := errs[code]; !ok { - code = 500 - } - - switch c.Type() { - case "text/plain": - c.Send(code, info) - default: - c.Send(code, &err{ - errs[code].Code, - errs[code].Details, - errs[code].Description, - info, - }) - } - -} - -type err struct { - Code int `codec:"code,omitempty"` - Details string `codec:"details,omitempty"` - Description string `codec:"description,omitempty"` - Information string `codec:"information,omitempty"` -} - -var errs = map[int]*err{ - - 200: { - Code: 200, - Details: "Information", - Description: "Visit the documentation for details on accessing the api.", - }, - - 400: { - Code: 400, - Details: "Request problems detected", - Description: "There is a problem with your request. Ensure that the request is valid.", - }, - - 401: { - Code: 401, - Details: "Authentication failed", - Description: "Your authentication details are invalid. Reauthenticate using a valid token.", - }, - - 403: { - Code: 403, - Details: "Request resource forbidden", - Description: "Your request was forbidden. Perhaps you don't have the necessary permissions to access this resource.", - }, - - 404: { - Code: 404, - Details: "Request resource not found", - Description: "The requested resource does not exist. Check that you have entered the url correctly.", - }, - - 405: { - Code: 405, - Details: "This method is not allowed", - Description: "The requested http method is not allowed for this resource. Refer to the documentation for allowed methods.", - }, - - 409: { - Code: 409, - Details: "Request conflict detected", - Description: "The request could not be processed because of a conflict in the request.", - }, - - 413: { - Code: 413, - Details: "Request content length too large", - Description: "All requests to the database must not exceed the predefined content length.", - }, - - 415: { - Code: 415, - Details: "Unsupported content type requested", - Description: "The request needs to adhere to certain constraints. Check your request settings and try again.", - }, - - 422: { - Code: 422, - Details: "Request problems detected", - Description: "There is a problem with your request. The request appears to contain invalid data.", - }, - - 426: { - Code: 426, - Details: "Upgrade required", - Description: "There is a problem with your request. The request is expected to upgrade to a websocket connection.", - }, - - 500: { - Code: 500, - Details: "Internal server error", - Description: "There was a problem with our servers, and we have been notified.", - }, - - 501: { - Code: 501, - Details: "Not Implemented", - Description: "The server either does not recognize the request method, or it lacks the ability to fulfill the request.", - }, - - 504: { - Code: 504, - Details: "Gateway Timeout", - Description: "The request to the server was restricted by a timeout duration, and did not manage to complete in time.", - }, -} diff --git a/web/export.go b/web/export.go deleted file mode 100644 index c4ee0725..00000000 --- a/web/export.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/db" -) - -func export(c *fibre.Context) (err error) { - - if c.Get("auth").(*cnf.Auth).Kind >= cnf.AuthSC { - return fibre.NewHTTPError(401) - } - - c.Response().Header().Set("Content-Type", "application/octet-stream") - - return db.Export(c, c.Request().Header().Get("NS"), c.Request().Header().Get("DB")) - -} diff --git a/web/live.go b/web/live.go deleted file mode 100644 index 74e1b903..00000000 --- a/web/live.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -//, -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/db" -) - -func live() fibre.MiddlewareFunc { - return func(h fibre.HandlerFunc) fibre.HandlerFunc { - return func(c *fibre.Context) (err error) { - - if c.IsSocket() { - beg, end := db.Socket(c, c.Uniq()) - beg() - err = h(c) - end() - return err - } - - return h(c) - - } - } -} diff --git a/web/routes.go b/web/routes.go deleted file mode 100644 index 1bc1eda1..00000000 --- a/web/routes.go +++ /dev/null @@ -1,375 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "strconv" - "time" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/fibre/mw" - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/util/build" - "github.com/surrealdb/surrealdb/util/show" -) - -func limit(c *fibre.Context, i int64) int64 { - if s := c.Query("limit"); len(s) > 0 { - if x, err := strconv.ParseInt(s, 10, 64); err == nil { - if x > i { - return i - } - return x - } - } - return i -} - -func start(c *fibre.Context, i int64) int64 { - if s := c.Query("start"); len(s) > 0 { - if x, err := strconv.ParseInt(s, 10, 64); err == nil { - if x < i { - return i - } - return x - } - } - return i -} - -func versn(c *fibre.Context, i time.Time) time.Time { - if s := c.Query("version"); len(s) > 0 { - if x, err := time.Parse(sql.RFCNano, s); err == nil { - return x - } - } - return i -} - -func routes(s *fibre.Fibre) { - - s.Dir("/", "app/") - - // -------------------------------------------------- - // Endpoint for health checks - // -------------------------------------------------- - - s.Get("/info", func(c *fibre.Context) error { - return c.Send(200, build.GetInfo()) - }) - - // -------------------------------------------------- - // Endpoints for submitting rpc queries - // -------------------------------------------------- - - s.Rpc("/rpc", &rpc{}) - - s.Use(mw.Quit(&mw.QuitOpts{ - Timeout: 15 * time.Second, - }).PathIs("/rpc")) - - // -------------------------------------------------- - // Endpoints for syncing data - // -------------------------------------------------- - - s.Get("/sync", func(c *fibre.Context) error { - return syncer(c, true) // Export - }) - - s.Post("/sync", func(c *fibre.Context) error { - return syncer(c, false) // Import - }) - - s.Get("/export", func(c *fibre.Context) error { - return export(c) - }) - - s.Use(mw.Type(&mw.TypeOpts{ - AllowedContent: map[string]bool{ - "application/octet-stream": true, - }, - }).PathIs("/sync", "/export")) - - // -------------------------------------------------- - // Endpoints for authentication signup - // -------------------------------------------------- - - s.Options("/signup", func(c *fibre.Context) error { - return c.Code(200) - }) - - s.Post("/signup", func(c *fibre.Context) error { - return signup(c) - }) - - s.Use(mw.Quit(&mw.QuitOpts{ - Timeout: 10 * time.Second, - }).PathIs("/signup")) - - s.Use(mw.Type(&mw.TypeOpts{ - AllowedContent: map[string]bool{ - "application/json": true, - "application/cork": true, - "application/cbor": true, - "application/msgpack": true, - "application/x-www-form-urlencoded": true, - }, - }).PathIs("/signup").MethodIsNot("OPTIONS")) - - // -------------------------------------------------- - // Endpoints for authentication signin - // -------------------------------------------------- - - s.Options("/signin", func(c *fibre.Context) error { - return c.Code(200) - }) - - s.Post("/signin", func(c *fibre.Context) error { - return signin(c) - }) - - s.Use(mw.Quit(&mw.QuitOpts{ - Timeout: 10 * time.Second, - }).PathIs("/signin")) - - s.Use(mw.Type(&mw.TypeOpts{ - AllowedContent: map[string]bool{ - "application/json": true, - "application/cork": true, - "application/cbor": true, - "application/msgpack": true, - "application/x-www-form-urlencoded": true, - }, - }).PathIs("/signin").MethodIsNot("OPTIONS")) - - // -------------------------------------------------- - // Endpoints for submitting sql queries - // -------------------------------------------------- - - s.Options("/sql", func(c *fibre.Context) error { - return c.Code(200) - }) - - s.Post("/sql", func(c *fibre.Context) error { - res, err := db.Execute(c, c.Request().Body, nil) - if err != nil { - return err - } - return c.Send(200, res) - }) - - s.Use(mw.Type(&mw.TypeOpts{ - AllowedContent: map[string]bool{ - "text/plain": true, - "application/json": true, - "application/cork": true, - "application/cbor": true, - "application/msgpack": true, - }, - }).PathIs("/sql").MethodIsNot("OPTIONS")) - - // -------------------------------------------------- - // Endpoints for submitting websocket sql - // -------------------------------------------------- - - s.Get("/sql", func(c *fibre.Context) error { - if err := c.Upgrade(); err != nil { - return err - } - for { - _, msg, err := c.Socket().Read() - if err != nil { - return err - } - if res, err := db.Execute(c, msg, nil); err != nil { - c.Socket().SendText(err.Error()) - } else { - c.Socket().SendJSON(res) - } - } - }) - - // -------------------------------------------------- - // Endpoints for manipulating multiple records - // -------------------------------------------------- - - s.Options("/key/:class", func(c *fibre.Context) error { - return c.Code(200) - }) - - s.Get("/key/:class", func(c *fibre.Context) error { - - txt := "SELECT * FROM $class LIMIT $limit START $start VERSION $versn" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "class": sql.NewTable(c.Param("class")), - "limit": limit(c, 100), - "start": start(c, 0), - "versn": versn(c, time.Now()), - }) - - return show.Output(c, c.Param("class"), show.Many, show.Select, res, err) - - }) - - s.Post("/key/:class", func(c *fibre.Context) error { - - var data interface{} - - if err := c.Bind(&data); err != nil { - return fibre.NewHTTPError(422) - } - - txt := "CREATE $class CONTENT $data RETURN AFTER" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "class": sql.NewTable(c.Param("class")), - "data": data, - }) - - return show.Output(c, c.Param("class"), show.Many, show.Create, res, err) - - }) - - s.Delete("/key/:class", func(c *fibre.Context) error { - - txt := "DELETE $class" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "class": sql.NewTable(c.Param("class")), - }) - - return show.Output(c, c.Param("class"), show.Many, show.Delete, res, err) - - }) - - // -------------------------------------------------- - // Endpoints for manipulating a single record - // -------------------------------------------------- - - s.Options("/key/:class/:id", func(c *fibre.Context) error { - return c.Code(200) - }) - - s.Get("/key/:class/:id", func(c *fibre.Context) error { - - txt := "SELECT * FROM $thing VERSION $versn" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "thing": sql.NewThing(c.Param("class"), c.Param("id")), - "versn": versn(c, time.Now()), - }) - - return show.Output(c, c.Param("class"), show.One, show.Select, res, err) - - }) - - s.Post("/key/:class/:id", func(c *fibre.Context) error { - - var data interface{} - - if err := c.Bind(&data); err != nil { - return fibre.NewHTTPError(422) - } - - txt := "CREATE $thing CONTENT $data RETURN AFTER" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "thing": sql.NewThing(c.Param("class"), c.Param("id")), - "data": data, - }) - - return show.Output(c, c.Param("class"), show.One, show.Create, res, err) - - }) - - s.Put("/key/:class/:id", func(c *fibre.Context) error { - - var data interface{} - - if err := c.Bind(&data); err != nil { - return fibre.NewHTTPError(422) - } - - txt := "UPDATE $thing CONTENT $data RETURN AFTER" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "thing": sql.NewThing(c.Param("class"), c.Param("id")), - "data": data, - }) - - return show.Output(c, c.Param("class"), show.One, show.Update, res, err) - - }) - - s.Patch("/key/:class/:id", func(c *fibre.Context) error { - - var data interface{} - - if err := c.Bind(&data); err != nil { - return fibre.NewHTTPError(422) - } - - txt := "UPDATE $thing DIFF $data RETURN DIFF" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "thing": sql.NewThing(c.Param("class"), c.Param("id")), - "data": data, - }) - - return show.Output(c, c.Param("class"), show.One, show.Modify, res, err) - - }) - - s.Trace("/key/:class/:id", func(c *fibre.Context) error { - - txt := "SELECT HISTORY FROM $thing" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "thing": sql.NewThing(c.Param("class"), c.Param("id")), - }) - - return show.Output(c, c.Param("class"), show.One, show.Trace, res, err) - - }) - - s.Delete("/key/:class/:id", func(c *fibre.Context) error { - - txt := "DELETE $thing" - - res, err := db.Execute(c, txt, map[string]interface{}{ - "thing": sql.NewThing(c.Param("class"), c.Param("id")), - }) - - return show.Output(c, c.Param("class"), show.One, show.Delete, res, err) - - }) - - s.Use(mw.Quit(&mw.QuitOpts{ - Timeout: 5 * time.Second, - }).PathBegsWith("/key/")) - - s.Use(mw.Type(&mw.TypeOpts{ - AllowedContent: map[string]bool{ - "application/json": true, - "application/cork": true, - "application/cbor": true, - "application/msgpack": true, - "application/vnd.api+json": true, - }, - }).PathBegsWith("/key/").MethodIsNot("OPTIONS")) - -} diff --git a/web/rpc.go b/web/rpc.go deleted file mode 100644 index 423634e5..00000000 --- a/web/rpc.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/sql" -) - -type rpc struct{} - -// -------------------------------------------------- -// Methods for authentication -// -------------------------------------------------- - -func (r *rpc) Ping(c *fibre.Context) (interface{}, error) { - return "OK", nil -} - -func (r *rpc) Info(c *fibre.Context) (interface{}, error) { - return c.Get("auth").(*cnf.Auth).Data, nil -} - -func (r *rpc) Signup(c *fibre.Context, vars map[string]interface{}) (interface{}, error) { - return signupRpc(c, vars) -} - -func (r *rpc) Signin(c *fibre.Context, vars map[string]interface{}) (interface{}, error) { - return signinRpc(c, vars) -} - -func (r *rpc) Invalidate(c *fibre.Context) (interface{}, error) { - return c.Get("auth").(*cnf.Auth).Reset().Data, nil -} - -func (r *rpc) Authenticate(c *fibre.Context, auth string) (interface{}, error) { - return c.Get("auth").(*cnf.Auth).Reset().Data, checkBearer(c, auth, ignore) -} - -// -------------------------------------------------- -// Methods for live queries -// -------------------------------------------------- - -func (r *rpc) Kill(c *fibre.Context, query string) (interface{}, error) { - return db.Execute(c, "KILL $query", map[string]interface{}{ - "query": query, - }) -} - -func (r *rpc) Live(c *fibre.Context, class string) (interface{}, error) { - return db.Execute(c, "LIVE SELECT * FROM $class", map[string]interface{}{ - "class": sql.NewTable(class), - }) -} - -// -------------------------------------------------- -// Methods for static queries -// -------------------------------------------------- - -func (r *rpc) Let(c *fibre.Context, key string, val interface{}) (interface{}, error) { - switch val := val.(type) { - case *fibre.RPCNull: - vars := c.Get("vars").(map[string]interface{}) - delete(vars, key) - c.Set("vars", vars) - return vars, nil - default: - vars := c.Get("vars").(map[string]interface{}) - vars[key] = val - c.Set("vars", vars) - return vars, nil - } -} - -func (r *rpc) Query(c *fibre.Context, sql string, vars map[string]interface{}) (interface{}, error) { - return db.Execute(c, sql, vars) -} - -func (r *rpc) Select(c *fibre.Context, class string, thing interface{}) (interface{}, error) { - switch thing := thing.(type) { - case *fibre.RPCNull: - return db.Execute(c, "SELECT * FROM $class", map[string]interface{}{ - "class": sql.NewTable(class), - }) - case []interface{}: - return db.Execute(c, "SELECT * FROM $batch", map[string]interface{}{ - "batch": sql.NewBatch(class, thing), - }) - default: - return db.Execute(c, "SELECT * FROM $thing", map[string]interface{}{ - "thing": sql.NewThing(class, thing), - }) - } -} - -func (r *rpc) Create(c *fibre.Context, class string, thing interface{}, data map[string]interface{}) (interface{}, error) { - switch thing := thing.(type) { - case *fibre.RPCNull: - return db.Execute(c, "CREATE $class CONTENT $data RETURN AFTER", map[string]interface{}{ - "class": sql.NewTable(class), - "data": data, - }) - case []interface{}: - return db.Execute(c, "CREATE $batch CONTENT $data RETURN AFTER", map[string]interface{}{ - "batch": sql.NewBatch(class, thing), - "data": data, - }) - default: - return db.Execute(c, "CREATE $thing CONTENT $data RETURN AFTER", map[string]interface{}{ - "thing": sql.NewThing(class, thing), - "data": data, - }) - } -} - -func (r *rpc) Update(c *fibre.Context, class string, thing interface{}, data map[string]interface{}) (interface{}, error) { - switch thing := thing.(type) { - case *fibre.RPCNull: - return db.Execute(c, "UPDATE $class CONTENT $data RETURN AFTER", map[string]interface{}{ - "class": sql.NewTable(class), - "data": data, - }) - case []interface{}: - return db.Execute(c, "UPDATE $batch CONTENT $data RETURN AFTER", map[string]interface{}{ - "batch": sql.NewBatch(class, thing), - "data": data, - }) - default: - return db.Execute(c, "UPDATE $thing CONTENT $data RETURN AFTER", map[string]interface{}{ - "thing": sql.NewThing(class, thing), - "data": data, - }) - } -} - -func (r *rpc) Change(c *fibre.Context, class string, thing interface{}, data map[string]interface{}) (interface{}, error) { - switch thing := thing.(type) { - case *fibre.RPCNull: - return db.Execute(c, "UPDATE $class MERGE $data RETURN AFTER", map[string]interface{}{ - "class": sql.NewTable(class), - "data": data, - }) - case []interface{}: - return db.Execute(c, "UPDATE $batch MERGE $data RETURN AFTER", map[string]interface{}{ - "batch": sql.NewBatch(class, thing), - "data": data, - }) - default: - return db.Execute(c, "UPDATE $thing MERGE $data RETURN AFTER", map[string]interface{}{ - "thing": sql.NewThing(class, thing), - "data": data, - }) - } -} - -func (r *rpc) Modify(c *fibre.Context, class string, thing interface{}, data []interface{}) (interface{}, error) { - switch thing := thing.(type) { - case *fibre.RPCNull: - return db.Execute(c, "UPDATE $class DIFF $data RETURN AFTER", map[string]interface{}{ - "class": sql.NewTable(class), - "data": data, - }) - case []interface{}: - return db.Execute(c, "UPDATE $batch DIFF $data RETURN AFTER", map[string]interface{}{ - "batch": sql.NewBatch(class, thing), - "data": data, - }) - default: - return db.Execute(c, "UPDATE $thing DIFF $data RETURN AFTER", map[string]interface{}{ - "thing": sql.NewThing(class, thing), - "data": data, - }) - } -} - -func (r *rpc) Delete(c *fibre.Context, class string, thing interface{}) (interface{}, error) { - switch thing := thing.(type) { - case *fibre.RPCNull: - return db.Execute(c, "DELETE $class", map[string]interface{}{ - "class": sql.NewTable(class), - }) - case []interface{}: - return db.Execute(c, "DELETE $batch", map[string]interface{}{ - "batch": sql.NewBatch(class, thing), - }) - default: - return db.Execute(c, "DELETE $thing", map[string]interface{}{ - "thing": sql.NewThing(class, thing), - }) - } -} diff --git a/web/sess.go b/web/sess.go deleted file mode 100644 index a60b7c5f..00000000 --- a/web/sess.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" -) - -func sess() fibre.MiddlewareFunc { - return func(h fibre.HandlerFunc) fibre.HandlerFunc { - return func(c *fibre.Context) (err error) { - vars := make(map[string]interface{}) - c.Set(varKeyVars, vars) - return h(c) - } - } -} diff --git a/web/signin.go b/web/signin.go deleted file mode 100644 index 57499f78..00000000 --- a/web/signin.go +++ /dev/null @@ -1,429 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "time" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" - "github.com/surrealdb/surrealdb/util/data" - "github.com/dgrijalva/jwt-go" - "golang.org/x/crypto/bcrypt" -) - -func signin(c *fibre.Context) (err error) { - - var vars map[string]interface{} - - c.Bind(&vars) - - str, err := signinInternal(c, vars) - - switch err { - case nil: - return c.Send(200, str) - default: - return err - } - -} - -func signinRpc(c *fibre.Context, vars map[string]interface{}) (res interface{}, err error) { - - var str string - - str, err = signinInternal(c, vars) - if err != nil { - return nil, err - } - - err = checkBearer(c, str, ignore) - if err != nil { - return nil, err - } - - return str, nil - -} - -func signinInternal(c *fibre.Context, vars map[string]interface{}) (str string, err error) { - - n, nok := vars[varKeyNs].(string) - d, dok := vars[varKeyDb].(string) - s, sok := vars[varKeySc].(string) - - // If we have a namespace, database, and - // scope defined, then we are logging in - // to the scope level. - - if nok && len(n) > 0 && dok && len(d) > 0 && sok && len(s) > 0 { - - var ok bool - var tx *txn.TX - var doc *sql.Thing - var res []*db.Response - var exp *sql.SubExpression - var evt *sql.MultExpression - var scp *sql.DefineScopeStatement - - // Start a new read transaction. - - if tx, err = txn.New(c.Context(), false); err != nil { - return str, fibre.NewHTTPError(500) - } - - // Ensure the transaction closes. - - defer tx.Cancel() - - // Get the current context. - - ctx := c.Context() - - // Create a temporary context. - - t := fibre.NewContext( - c.Request(), - c.Response(), - c.Fibre(), - ) - - // Ensure we copy the session id. - - t.Set(varKeyUniq, c.Get(varKeyUniq)) - - // Give full permissions to scope. - - t.Set(varKeyAuth, &cnf.Auth{Kind: cnf.AuthDB, NS: n, DB: d}) - - // Specify fields to show in logs. - - f := map[string]interface{}{"ns": n, "db": d, "sc": s} - - // Get the specified signin scope. - - if scp, err = tx.GetSC(ctx, n, d, s); err != nil { - m := "Authentication scope does not exist" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Check that the scope allows signin. - - if exp, ok = scp.Signin.(*sql.SubExpression); !ok { - m := "Authentication scope does not allow signin" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Process the scope signin statement. - - query := &sql.Query{Statements: []sql.Statement{exp.Expr}} - - // If the query fails then return a 501 error. - - if res, err = db.Process(t, query, vars); err != nil { - m := "Authentication scope signin was unsuccessful: Query failed" - return str, fibre.NewHTTPError(501).WithFields(f).WithMessage(m) - } - - // If the response is not 1 record then return a 403 error. - - if len(res) != 1 { - m := "Authentication scope signin was unsuccessful: Query failed" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // If the response has an error set then return a 403 error. - - if res[0].Status != "OK" { - m := "Authentication scope signin was unsuccessful: " + res[0].Detail - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // If the response has no record set then return a 403 error. - - if len(res[0].Result) != 1 { - m := "Authentication scope signin was unsuccessful: No record returned" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // If the query does not return an id field then return a 403 error. - - if doc, ok = data.Consume(res[0].Result[0]).Get("id").Data().(*sql.Thing); !ok { - m := "Authentication scope signin was unsuccessful: No id field found" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Create a new token signer with the default claims. - - signr := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{ - "NS": n, - "DB": d, - "SC": s, - "TK": "default", - "IP": c.IP().String(), - "iss": "Surreal", - "iat": time.Now().Unix(), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(scp.Time).Unix(), - "TB": doc.TB, - "ID": doc.ID, - }) - - // Try to create the final signed token as a string. - - if str, err = signr.SignedString(scp.Code); err != nil { - m := "Problem with signing method: " + err.Error() - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Check that the scope allows signup. - - if evt, ok = scp.OnSignin.(*sql.MultExpression); ok { - - stmts := make([]sql.Statement, len(evt.Expr)) - - for k := range evt.Expr { - stmts[k] = evt.Expr[k] - } - - query := &sql.Query{Statements: stmts} - - qvars := map[string]interface{}{ - "id": doc, - } - - // If the query fails then return a 501 error. - - if res, err = db.Process(t, query, qvars); err != nil { - m := "Authentication scope signin was unsuccessful: `ON SIGNIN` failed:" + err.Error() - return str, fibre.NewHTTPError(501).WithFields(f).WithMessage(m) - } - - } - - return str, err - - } - - // If we have a namespace, database, but - // no scope defined, then we are logging - // in to the database level. - - if nok && len(n) > 0 && dok && len(d) > 0 { - - var str string - var usr *sql.DefineLoginStatement - - // Get the specified user and password. - - u, uok := vars[varKeyUser].(string) - p, pok := vars[varKeyPass].(string) - - // Specify fields to show in logs. - - f := map[string]interface{}{"ns": n, "db": d, "du": u} - - // Check that the required fields exist. - - if !uok || !pok { - m := "Username or password is missing" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Start a new read transaction. - - if usr, err = signinDB(c, n, d, u, p); err != nil { - return str, err - } - - // Create a new token signer with the default claims. - - signr := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{ - "US": u, - "NS": n, - "DB": d, - "TK": "default", - "IP": c.IP().String(), - "iss": "Surreal", - "iat": time.Now().Unix(), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(1 * time.Hour).Unix(), - }) - - // Try to create the final signed token as a string. - - if str, err = signr.SignedString(usr.Code); err != nil { - m := "Problem with signing method: " + err.Error() - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - return str, err - - } - - // If we have a namespace, but no database, - // or scope defined, then we are logging - // in to the namespace level. - - if nok && len(n) > 0 { - - var str string - var usr *sql.DefineLoginStatement - - // Get the specified user and password. - - u, uok := vars[varKeyUser].(string) - p, pok := vars[varKeyPass].(string) - - // Specify fields to show in logs. - - f := map[string]interface{}{"ns": n, "nu": u} - - // Check that the required fields exist. - - if !uok || !pok { - m := "Username or password is missing" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - if usr, err = signinNS(c, n, u, p); err != nil { - return str, err - } - - // Create a new token signer with the default claims. - - signr := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{ - "US": u, - "NS": n, - "TK": "default", - "IP": c.IP().String(), - "iss": "Surreal", - "iat": time.Now().Unix(), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(1 * time.Hour).Unix(), - }) - - // Try to create the final signed token as a string. - - if str, err = signr.SignedString(usr.Code); err != nil { - m := "Problem with signing method: " + err.Error() - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - return str, err - - } - - return str, fibre.NewHTTPError(403) - -} - -func signinDB(c *fibre.Context, n, d, u, p string) (usr *sql.DefineLoginStatement, err error) { - - var tx *txn.TX - - // Start a new read transaction. - - if tx, err = txn.New(c.Context(), false); err != nil { - return nil, fibre.NewHTTPError(500) - } - - // Ensure the transaction closes. - - defer tx.Cancel() - - // Get the current context. - - ctx := c.Context() - - // Specify fields to show in logs. - - f := map[string]interface{}{"ns": n, "db": d, "du": u} - - // Get the specified user and password. - - if len(u) == 0 || len(p) == 0 { - m := "Database signin was unsuccessful" - return nil, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Get the specified namespace login. - - if usr, err = tx.GetDU(ctx, n, d, u); err != nil { - m := "Database login does not exist" - return nil, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Compare the hashed and stored passwords. - - if err = bcrypt.CompareHashAndPassword(usr.Pass, []byte(p)); err != nil { - m := "Database signin was unsuccessful" - return nil, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - return - -} - -func signinNS(c *fibre.Context, n, u, p string) (usr *sql.DefineLoginStatement, err error) { - - var tx *txn.TX - - // Start a new read transaction. - - if tx, err = txn.New(c.Context(), false); err != nil { - return nil, fibre.NewHTTPError(500) - } - - // Ensure the transaction closes. - - defer tx.Cancel() - - // Get the current context. - - ctx := c.Context() - - // Specify fields to show in logs. - - f := map[string]interface{}{"ns": n, "nu": u} - - // Get the specified user and password. - - if len(u) == 0 || len(p) == 0 { - m := "Namespace signin was unsuccessful" - return nil, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Get the specified namespace login. - - if usr, err = tx.GetNU(ctx, n, u); err != nil { - m := "Namespace login does not exist" - return nil, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Compare the hashed and stored passwords. - - if err = bcrypt.CompareHashAndPassword(usr.Pass, []byte(p)); err != nil { - m := "Namespace signin was unsuccessful" - return nil, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - return - -} diff --git a/web/signup.go b/web/signup.go deleted file mode 100644 index c3520bb8..00000000 --- a/web/signup.go +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "time" - - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/db" - "github.com/surrealdb/surrealdb/sql" - "github.com/surrealdb/surrealdb/txn" - "github.com/surrealdb/surrealdb/util/data" - "github.com/dgrijalva/jwt-go" -) - -func signup(c *fibre.Context) (err error) { - - var vars map[string]interface{} - - c.Bind(&vars) - - str, err := signupInternal(c, vars) - - switch err { - case nil: - return c.Send(200, str) - default: - return err - } - -} - -func signupRpc(c *fibre.Context, vars map[string]interface{}) (res interface{}, err error) { - - var str string - - str, err = signupInternal(c, vars) - if err != nil { - return nil, err - } - - err = checkBearer(c, str, ignore) - if err != nil { - return nil, err - } - - return str, nil - -} - -func signupInternal(c *fibre.Context, vars map[string]interface{}) (str string, err error) { - - n, nok := vars[varKeyNs].(string) - d, dok := vars[varKeyDb].(string) - s, sok := vars[varKeySc].(string) - - // If we have a namespace, database, and - // scope defined, then we are logging in - // to the scope level. - - if nok && len(n) > 0 && dok && len(d) > 0 && sok && len(s) > 0 { - - var ok bool - var tx *txn.TX - var doc *sql.Thing - var res []*db.Response - var exp *sql.SubExpression - var evt *sql.MultExpression - var scp *sql.DefineScopeStatement - - // Start a new read transaction. - - if tx, err = txn.New(c.Context(), false); err != nil { - return str, fibre.NewHTTPError(500) - } - - // Ensure the transaction closes. - - defer tx.Cancel() - - // Get the current context. - - ctx := c.Context() - - // Create a temporary context. - - t := fibre.NewContext( - c.Request(), - c.Response(), - c.Fibre(), - ) - - // Ensure we copy the session id. - - t.Set(varKeyUniq, c.Get(varKeyUniq)) - - // Give full permissions to scope. - - t.Set(varKeyAuth, &cnf.Auth{Kind: cnf.AuthDB, NS: n, DB: d}) - - // Specify fields to show in logs. - - f := map[string]interface{}{"ns": n, "db": d, "sc": s} - - // Get the specified signin scope. - - if scp, err = tx.GetSC(ctx, n, d, s); err != nil { - m := "Authentication scope does not exist" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Check that the scope allows signup. - - if exp, ok = scp.Signup.(*sql.SubExpression); !ok { - m := "Authentication scope does not allow signup" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Process the scope signup statement. - - query := &sql.Query{Statements: []sql.Statement{exp.Expr}} - - // If the query fails then return a 501 error. - - if res, err = db.Process(t, query, vars); err != nil { - m := "Authentication scope signup was unsuccessful: Query failed" - return str, fibre.NewHTTPError(501).WithFields(f).WithMessage(m) - } - - // If the response is not 1 record then return a 403 error. - - if len(res) != 1 { - m := "Authentication scope signup was unsuccessful: Query failed" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // If the response has an error set then return a 403 error. - - if res[0].Status != "OK" { - m := "Authentication scope signin was unsuccessful: " + res[0].Detail - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // If the response has no record set then return a 403 error. - - if len(res[0].Result) != 1 { - m := "Authentication scope signup was unsuccessful: No record created" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // If the query does not return an id field then return a 403 error. - - if doc, ok = data.Consume(res[0].Result[0]).Get("id").Data().(*sql.Thing); !ok { - m := "Authentication scope signup was unsuccessful: No id field found" - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Create a new token signer with the default claims. - - signr := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{ - "NS": n, - "DB": d, - "SC": s, - "TK": "default", - "IP": c.IP().String(), - "iss": "Surreal", - "iat": time.Now().Unix(), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(scp.Time).Unix(), - "TB": doc.TB, - "ID": doc.ID, - }) - - // Try to create the final signed token as a string. - - if str, err = signr.SignedString(scp.Code); err != nil { - m := "Problem with signing method: " + err.Error() - return str, fibre.NewHTTPError(403).WithFields(f).WithMessage(m) - } - - // Check that the scope allows signup. - - if evt, ok = scp.OnSignup.(*sql.MultExpression); ok { - - stmts := make([]sql.Statement, len(evt.Expr)) - - for k := range evt.Expr { - stmts[k] = evt.Expr[k] - } - - query := &sql.Query{Statements: stmts} - - qvars := map[string]interface{}{ - "id": doc, - } - - // If the query fails then return a 501 error. - - if res, err = db.Process(t, query, qvars); err != nil { - m := "Authentication scope signup was unsuccessful: `ON SIGNUP` failed:" + err.Error() - return str, fibre.NewHTTPError(501).WithFields(f).WithMessage(m) - } - - } - - return str, err - - } - - return str, fibre.NewHTTPError(403) - -} diff --git a/web/sync.go b/web/sync.go deleted file mode 100644 index b7aaf1fc..00000000 --- a/web/sync.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/db" -) - -func syncer(c *fibre.Context, sync bool) (err error) { - - if c.Get("auth").(*cnf.Auth).Kind != cnf.AuthKV { - return fibre.NewHTTPError(401) - } - - c.Response().Header().Set("Content-Type", "application/octet-stream") - - switch sync { - case true: - return db.Sync(c.Response()) - case false: - return db.Sync(c.Request().Body) - } - - return nil - -} diff --git a/web/vars.go b/web/vars.go deleted file mode 100644 index f3f54a14..00000000 --- a/web/vars.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -const ( - varKeyNs = "NS" - varKeyDb = "DB" - varKeySc = "SC" - varKeyTk = "TK" - varKeyUs = "US" - varKeyTb = "TB" - varKeyId = "ID" - varKeyAuth = "auth" - varKeyVars = "vars" - varKeyUser = "user" - varKeyPass = "pass" - varKeyUniq = "uniq" -) diff --git a/web/web.go b/web/web.go deleted file mode 100644 index bca70108..00000000 --- a/web/web.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright © 2016 SurrealDB Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -//, -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package web - -import ( - "github.com/surrealdb/fibre" - "github.com/surrealdb/fibre/mw" - - "github.com/surrealdb/surrealdb/cnf" - "github.com/surrealdb/surrealdb/log" -) - -// Setup sets up the server for remote connections -func Setup(opts *cnf.Options) (err error) { - - log.WithPrefix("web").Infof("Starting web server on %s", opts.Conn) - - s := fibre.Server() - - routes(s) - s.SetName("web") - s.SetIdleTimeout("5s") - s.SetReadTimeout("30s") - s.SetWriteTimeout("300s") - s.SetHTTPErrorHandler(errors) - s.Logger().SetLogger(log.Instance()) - - // Setup middleware - - s.Use(mw.Uniq()) // Add uniq id - s.Use(mw.Fail()) // Catch panics - s.Use(mw.Logs()) // Log requests - - // Add cors headers - - s.Use(mw.Cors(&mw.CorsOpts{ - AllowedOrigin: "*", - AllowedMethods: []string{ - "GET", - "PUT", - "POST", - "PATCH", - "DELETE", - "TRACE", - "OPTIONS", - }, - AllowedHeaders: []string{ - "Accept", - "Authorization", - "Content-Type", - "Origin", - "NS", - "DB", - "ID", - }, - AccessControlMaxAge: 1800, - })) - - // Check body size - - s.Use(mw.Size(&mw.SizeOpts{ - AllowedLength: 1 << 20, // 1mb - })) - - // Setup authentication - - s.Use(sess()) - - // Setup authentication - - s.Use(auth()) - - // Setup live queries - - s.Use(live()) - - // Redirect non-https - - s.Use(mw.Secure(&mw.SecureOpts{ - RedirectHTTP: len(opts.Cert.Crt) != 0 || len(opts.Cert.Key) != 0, - })) - - // Log successful start - - log.WithPrefix("web").Infof("Started web server on %s", opts.Conn) - - // Run the server - - if len(opts.Cert.Crt) == 0 || len(opts.Cert.Key) == 0 { - s.Run(opts.Conn) - } - - if len(opts.Cert.Crt) != 0 && len(opts.Cert.Key) != 0 { - s.Run(opts.Conn, opts.Cert.Crt, opts.Cert.Key) - } - - return nil - -} - -// Exit tears down the server gracefully -func Exit(opts *cnf.Options) (err error) { - log.WithPrefix("web").Infof("Shutting down web server on %s", opts.Conn) - return -}