Move license from MIT to Apache 2.0. Add Makefile

This commit is contained in:
Vikram Rangnekar 2019-11-28 01:25:46 -05:00
parent aff2a13ba4
commit 9ebd03fa8c
42 changed files with 885 additions and 210 deletions

3
.gitignore vendored
View File

@ -27,8 +27,11 @@
main main
.DS_Store .DS_Store
.swp .swp
.release
main main
super-graph super-graph
supergraph
*-fuzz.zip *-fuzz.zip
crashers crashers
suppressions suppressions
release

View File

@ -6,13 +6,13 @@ RUN yarn
RUN yarn build RUN yarn build
# stage: 2 # stage: 2
FROM golang:1.13beta1-alpine as go-build FROM golang:1.13.4-alpine as go-build
RUN apk update && \ RUN apk update && \
apk add --no-cache make && \
apk add --no-cache git && \ apk add --no-cache git && \
apk add --no-cache upx=3.95-r2 apk add --no-cache upx=3.95-r2
RUN go get -u github.com/rafaelsq/wtc && \ RUN go get -u github.com/rafaelsq/wtc
go get -u github.com/GeertJohan/go.rice/rice
WORKDIR /app WORKDIR /app
COPY . /app COPY . /app
@ -20,11 +20,9 @@ COPY . /app
RUN mkdir -p /app/web/build RUN mkdir -p /app/web/build
COPY --from=react-build /web/build/ ./web/build/ COPY --from=react-build /web/build/ ./web/build/
ENV GO111MODULE=on
RUN go mod vendor RUN go mod vendor
RUN go generate ./... && \ RUN make build
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o super-graph && \ RUN echo "Compressing binary, will take a bit of time..." && \
echo "Compressing binary, will take a bit of time..." && \
upx --ultra-brute -qq super-graph && \ upx --ultra-brute -qq super-graph && \
upx -t super-graph upx -t super-graph

189
LICENSE
View File

@ -1,21 +1,176 @@
The MIT License (MIT) Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2019-present Vikram Rangnekar. twitter.com/dosco TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy 1. Definitions.
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in "License" shall mean the terms and conditions for use, reproduction,
all copies or substantial portions of the Software. and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "Licensor" shall mean the copyright owner or entity authorized by
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, the copyright owner that is granting the License.
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "Legal Entity" shall mean the union of the acting entity and all
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, other entities that control, are controlled by, or are under common
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN control with that entity. For the purposes of this definition,
THE SOFTWARE. "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

93
Makefile Normal file
View File

@ -0,0 +1,93 @@
BUILD ?= $(shell git rev-parse --short HEAD)
BUILD_DATE ?= $(shell git log -1 --format=%ci)
BUILD_BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
BUILD_VERSION ?= $(shell git describe --always --tags)
PKGS := $(shell go list ./... | grep -v /vendor)
GOPATH ?= $(shell go env GOPATH)
ifndef GOPATH
override GOPATH = $(HOME)/go
endif
export GO111MODULE := on
# Build-time Go variables
version = github.com/dosco/super-graph/serv.version
gitBranch = github.com/dosco/super-graph/serv.gitBranch
lastCommitSHA = github.com/dosco/super-graph/serv.lastCommitSHA
lastCommitTime = github.com/dosco/super-graph/serv.lastCommitTime
BUILD_FLAGS ?= -ldflags '-s -w -X ${lastCommitSHA}=${BUILD} -X "${lastCommitTime}=${BUILD_DATE}" -X "${version}=${BUILD_VERSION}" -X ${gitBranch}=${BUILD_BRANCH}'
.PHONY: all build gen clean test run lint release version help $(PLATFORMS) $(BINARY)
test: lint
@go test -v $(PKGS)
BIN_DIR := $(GOPATH)/bin
GOLANGCILINT := $(BIN_DIR)/golangci-lint
$(GOLANGCILINT):
@curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b $(GOPATH)/bin v1.21.0
lint: $(GOMETALINTER)
@golangci-lint run ./... --skip-dirs-use-default
BINARY := super-graph
LDFLAGS := -s -w
PLATFORMS := windows linux darwin
os = $(word 1, $@)
$(PLATFORMS): gen
@mkdir -p release
@GOOS=$(os) GOARCH=amd64 go build $(BUILD_FLAGS) -o release/$(BINARY)-$(BUILD_VERSION)-$(os)-amd64
release: windows linux darwin
all: $(BINARY)
build: $(BINARY)
gen:
@go install github.com/GeertJohan/go.rice/rice
@go generate ./...
$(BINARY): clean gen
@go build $(BUILD_FLAGS) -o $(BINARY)
clean:
@rm -f $(BINARY)
run: clean
@go run $(BUILD_FLAGS) main.go $(ARGS)
install: gen
@echo $(GOPATH)
@echo "Commit Hash: `git rev-parse HEAD`"
@echo "Old Hash: `shasum $(GOPATH)/bin/$(BINARY) 2>/dev/null | cut -c -32`"
@go install $(BUILD_FLAGS)
@echo "New Hash:" `shasum $(GOPATH)/bin/$(BINARY) 2>/dev/null | cut -c -32`
uninstall: clean
@go clean -i -x
version:
@echo Super Graph ${BUILD_VERSION}
@echo Build: ${BUILD}
@echo Build date: ${BUILD_DATE}
@echo Branch: ${BUILD_BRANCH}
@echo Go version: $(shell go version)
help:
@echo
@echo Build commands:
@echo " make build - Build supergraph binary"
@echo " make install - Install supergraph binary"
@echo " make uninstall - Uninstall supergraph binary"
@echo " make [platform] - Build for platform [linux|darwin|windows]"
@echo " make release - Build all platforms"
@echo " make run - Run supergraph (eg. make run ARGS=\"version\")"
@echo " make version - Show current build info"
@echo " make help - This help"
@echo

13
NOTICE Normal file
View File

@ -0,0 +1,13 @@
Copyright 2019 Vikram Rangnekar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,10 +1,10 @@
<a href="https://supergraph.dev"><img src="https://supergraph.dev/hologram.svg" width="100" height="100" align="right" /></a> <a href="https://supergraph.dev"><img src="https://supergraph.dev/hologram.svg" width="100" height="100" align="right" /></a>
# Super Graph - Instant GraphQL APIs for your apps. # Super Graph
## Build web products faster. No code needed. GraphQL auto. transformed into efficient database queries. ### Build web products faster. Instant GraphQL API without writing any code. Works with Postgres. Also supports Rails apps.
![MIT license](https://img.shields.io/github/license/dosco/super-graph.svg) ![Apache Public License 2.0](https://img.shields.io/github/license/dosco/super-graph.svg)
![Docker build](https://img.shields.io/docker/cloud/build/dosco/super-graph.svg) ![Docker build](https://img.shields.io/docker/cloud/build/dosco/super-graph.svg)
![Cloud native](https://img.shields.io/badge/cloud--native-enabled-blue.svg) ![Cloud native](https://img.shields.io/badge/cloud--native-enabled-blue.svg)
[![Discord Chat](https://img.shields.io/discord/628796009539043348.svg)](https://discord.gg/6pSWCTZ) [![Discord Chat](https://img.shields.io/discord/628796009539043348.svg)](https://discord.gg/6pSWCTZ)
@ -56,7 +56,7 @@ Twitter or Discord.
## License ## License
[MIT](http://opensource.org/licenses/MIT) [Apache Public License 2.0](https://opensource.org/licenses/Apache-2.0)
Copyright (c) 2019-present Vikram Rangnekar Copyright (c) 2019-present Vikram Rangnekar

View File

@ -156,6 +156,8 @@ query getProducts {
products { products {
id id
name name
price
description
} }
} }

View File

@ -26,5 +26,5 @@ features:
- title: Free and Open Source - title: Free and Open Source
details: Not a VC funded startup. Not even a startup just good old open source code details: Not a VC funded startup. Not even a startup just good old open source code
footer: MIT Licensed | Copyright © 2018-present Vikram Rangnekar footer: Apache Public License 2.0 | Copyright © 2018-present Vikram Rangnekar
--- ---

View File

@ -147,9 +147,13 @@ Super Graph can generate your initial app for you. The generated app will have c
You can then add your database schema to the migrations, maybe create some seed data using the seed script and launch Super Graph. You're now good to go and can start working on your UI frontend in React, Vue or whatever. You can then add your database schema to the migrations, maybe create some seed data using the seed script and launch Super Graph. You're now good to go and can start working on your UI frontend in React, Vue or whatever.
```bash ```bash
# use the below command to download and install Super Graph. You will need Go 1.13 or above # Download and install Super Graph. You will need Go 1.13 or above
GO111MODULE=on go get -u github.com/dosco/super-graph git clone https://github.com/dosco/super-graph && cd super-graph && make install
```
And then create and launch you're new app
```bash
# create a new app and change to it's directory # create a new app and change to it's directory
super-graph new blog; cd blog super-graph new blog; cd blog
@ -1396,9 +1400,6 @@ brew install yarn
# yarn install dependencies and build the web ui # yarn install dependencies and build the web ui
(cd web && yarn install && yarn build) (cd web && yarn install && yarn build)
# generate some stuff the go code needs
go generate ./...
# do this the only the time to setup the database # do this the only the time to setup the database
docker-compose run rails_app rake db:create db:migrate db:seed docker-compose run rails_app rake db:create db:migrate db:seed
@ -1407,6 +1408,6 @@ docker-compose up
``` ```
## MIT License ## Apache License 2.0
MIT Licensed | Copyright © 2018-present Vikram Rangnekar Apache Public License 2.0 | Copyright © 2018-present Vikram Rangnekar

4
go.sum
View File

@ -1,6 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/GeertJohan/go.incremental v1.0.0 h1:7AH+pY1XUgQE4Y1HcXYaMqAI0m9yrFqo/jt0CW30vsg=
github.com/GeertJohan/go.incremental v1.0.0/go.mod h1:6fAjUhbVuX1KcMD3c8TEgVUqmo4seqhv0i0kdATSkM0= github.com/GeertJohan/go.incremental v1.0.0/go.mod h1:6fAjUhbVuX1KcMD3c8TEgVUqmo4seqhv0i0kdATSkM0=
github.com/GeertJohan/go.rice v1.0.0 h1:KkI6O9uMaQU3VEKaj01ulavtF7o1fWT7+pk/4voiMLQ= github.com/GeertJohan/go.rice v1.0.0 h1:KkI6O9uMaQU3VEKaj01ulavtF7o1fWT7+pk/4voiMLQ=
github.com/GeertJohan/go.rice v1.0.0/go.mod h1:eH6gbSOAUv07dQuZVnBmoDP8mgsM1rtixis4Tib9if0= github.com/GeertJohan/go.rice v1.0.0/go.mod h1:eH6gbSOAUv07dQuZVnBmoDP8mgsM1rtixis4Tib9if0=
@ -13,6 +14,7 @@ github.com/OneOfOne/xxhash v1.2.5 h1:zl/OfRA6nftbBK9qTohYBJ5xvw6C/oNKizR7cZGl3cI
github.com/OneOfOne/xxhash v1.2.5/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q= github.com/OneOfOne/xxhash v1.2.5/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=
github.com/adjust/gorails v0.0.0-20171013043634-2786ed0c03d3 h1:+qz9Ga6l6lKw6fgvk5RMV5HQznSLvI8Zxajwdj4FhFg= github.com/adjust/gorails v0.0.0-20171013043634-2786ed0c03d3 h1:+qz9Ga6l6lKw6fgvk5RMV5HQznSLvI8Zxajwdj4FhFg=
github.com/adjust/gorails v0.0.0-20171013043634-2786ed0c03d3/go.mod h1:FlkD11RtgMTYjVuBnb7cxoHmQGqvPpCsr2atC88nl/M= github.com/adjust/gorails v0.0.0-20171013043634-2786ed0c03d3/go.mod h1:FlkD11RtgMTYjVuBnb7cxoHmQGqvPpCsr2atC88nl/M=
github.com/akavel/rsrc v0.8.0 h1:zjWn7ukO9Kc5Q62DOJCcxGpXC18RawVtYAGdz2aLlfw=
github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c= github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
@ -140,6 +142,7 @@ github.com/jackc/puddle v1.0.0 h1:rbjAshlgKscNa7j0jAM0uNQflis5o2XUogPMVAwtcsM=
github.com/jackc/puddle v1.0.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle v1.0.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/tern v1.8.2 h1:+d9eK83fRS0dbf6nt+2tjILYF4FKG1O5xTFB8Lzc66U= github.com/jackc/tern v1.8.2 h1:+d9eK83fRS0dbf6nt+2tjILYF4FKG1O5xTFB8Lzc66U=
github.com/jackc/tern v1.8.2/go.mod h1:AMppp2oyCT6rYnJHLLMmPWwahfFvdIVi6mr9gH81Nxs= github.com/jackc/tern v1.8.2/go.mod h1:AMppp2oyCT6rYnJHLLMmPWwahfFvdIVi6mr9gH81Nxs=
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
@ -173,6 +176,7 @@ github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrk
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229 h1:E2B8qYyeSgv5MXpmzZXRNp8IAQ4vjxIjhpAf5hv/tAg=
github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229/go.mod h1:0aYXnNPJ8l7uZxf45rWW1a/uME32OF0rhiYGNQ2oF2E= github.com/nkovacs/streamquote v0.0.0-20170412213628-49af9bddb229/go.mod h1:0aYXnNPJ8l7uZxf45rWW1a/uME32OF0rhiYGNQ2oF2E=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=

View File

@ -139,7 +139,7 @@ func Filter(w *bytes.Buffer, b []byte, keys []string) error {
} }
if sk > 0 && sk < len(cb) { if sk > 0 && sk < len(cb) {
_, err = w.Write(cb[sk:len(cb)]) _, err = w.Write(cb[sk:])
} else { } else {
_, err = w.Write(cb) _, err = w.Write(cb)
} }

View File

@ -55,6 +55,6 @@ func TestFuzzCrashers(t *testing.T) {
} }
for _, f := range crashers { for _, f := range crashers {
unifiedTest([]byte(f)) _ = unifiedTest([]byte(f))
} }
} }

View File

@ -191,11 +191,11 @@ func TestGet(t *testing.T) {
} }
for i := range expected { for i := range expected {
if bytes.Equal(values[i].Key, expected[i].Key) == false { if !bytes.Equal(values[i].Key, expected[i].Key) {
t.Error(string(values[i].Key), " != ", string(expected[i].Key)) t.Error(string(values[i].Key), " != ", string(expected[i].Key))
} }
if bytes.Equal(values[i].Value, expected[i].Value) == false { if !bytes.Equal(values[i].Value, expected[i].Value) {
t.Error(string(values[i].Value), " != ", string(expected[i].Value)) t.Error(string(values[i].Value), " != ", string(expected[i].Value))
} }
} }
@ -225,7 +225,10 @@ func TestValue(t *testing.T) {
func TestFilter1(t *testing.T) { func TestFilter1(t *testing.T) {
var b bytes.Buffer var b bytes.Buffer
Filter(&b, []byte(input2), []string{"id", "full_name", "embed"}) err := Filter(&b, []byte(input2), []string{"id", "full_name", "embed"})
if err != nil {
t.Error(err)
}
expected := `[{"id": 1,"full_name": "Sidney Stroman","embed": {"id": 8,"full_name": "Caroll Orn Sr.","email": "joannarau@hegmann.io","__twitter_id": "ABC123"}},{"id": 2,"full_name": "Jerry Dickinson"}]` expected := `[{"id": 1,"full_name": "Sidney Stroman","embed": {"id": 8,"full_name": "Caroll Orn Sr.","email": "joannarau@hegmann.io","__twitter_id": "ABC123"}},{"id": 2,"full_name": "Jerry Dickinson"}]`
@ -238,7 +241,10 @@ func TestFilter2(t *testing.T) {
value := `[{"id":1,"customer_id":"cus_2TbMGf3cl0","object":"charge","amount":100,"amount_refunded":0,"date":"01/01/2019","application":null,"billing_details":{"address":"1 Infinity Drive","zipcode":"94024"}}, {"id":2,"customer_id":"cus_2TbMGf3cl0","object":"charge","amount":150,"amount_refunded":0,"date":"02/18/2019","billing_details":{"address":"1 Infinity Drive","zipcode":"94024"}},{"id":3,"customer_id":"cus_2TbMGf3cl0","object":"charge","amount":150,"amount_refunded":50,"date":"03/21/2019","billing_details":{"address":"1 Infinity Drive","zipcode":"94024"}}]` value := `[{"id":1,"customer_id":"cus_2TbMGf3cl0","object":"charge","amount":100,"amount_refunded":0,"date":"01/01/2019","application":null,"billing_details":{"address":"1 Infinity Drive","zipcode":"94024"}}, {"id":2,"customer_id":"cus_2TbMGf3cl0","object":"charge","amount":150,"amount_refunded":0,"date":"02/18/2019","billing_details":{"address":"1 Infinity Drive","zipcode":"94024"}},{"id":3,"customer_id":"cus_2TbMGf3cl0","object":"charge","amount":150,"amount_refunded":50,"date":"03/21/2019","billing_details":{"address":"1 Infinity Drive","zipcode":"94024"}}]`
var b bytes.Buffer var b bytes.Buffer
Filter(&b, []byte(value), []string{"id"}) err := Filter(&b, []byte(value), []string{"id"})
if err != nil {
t.Error(err)
}
expected := `[{"id":1},{"id":2},{"id":3}]` expected := `[{"id":1},{"id":2},{"id":3}]`
@ -253,7 +259,7 @@ func TestStrip(t *testing.T) {
expected := []byte(`[{"id":1,"embed":{"id":8}},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13}]`) expected := []byte(`[{"id":1,"embed":{"id":8}},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13}]`)
if bytes.Equal(value1, expected) == false { if !bytes.Equal(value1, expected) {
t.Log(value1) t.Log(value1)
t.Error("[Valid path] Does not match expected json") t.Error("[Valid path] Does not match expected json")
} }
@ -261,7 +267,7 @@ func TestStrip(t *testing.T) {
path2 := [][]byte{[]byte("boo"), []byte("hoo")} path2 := [][]byte{[]byte("boo"), []byte("hoo")}
value2 := Strip([]byte(input3), path2) value2 := Strip([]byte(input3), path2)
if bytes.Equal(value2, []byte(input3)) == false { if !bytes.Equal(value2, []byte(input3)) {
t.Log(value2) t.Log(value2)
t.Error("[Invalid path] Does not match expected json") t.Error("[Invalid path] Does not match expected json")
} }

View File

@ -16,8 +16,12 @@ func Replace(w *bytes.Buffer, b []byte, from, to []Field) error {
tmap := make(map[uint64]int, len(from)) tmap := make(map[uint64]int, len(from))
for i, f := range from { for i, f := range from {
h.Write(f.Key) if _, err := h.Write(f.Key); err != nil {
h.Write(f.Value) return err
}
if _, err := h.Write(f.Value); err != nil {
return err
}
tmap[h.Sum64()] = i tmap[h.Sum64()] = i
h.Reset() h.Reset()
@ -50,7 +54,9 @@ func Replace(w *bytes.Buffer, b []byte, from, to []Field) error {
case state == expectKeyClose && b[i] == '"': case state == expectKeyClose && b[i] == '"':
state = expectColon state = expectColon
h.Write(b[(s + 1):i]) if _, err := h.Write(b[(s + 1):i]); err != nil {
return err
}
we = s we = s
case state == expectColon && b[i] == ':': case state == expectColon && b[i] == ':':
@ -106,7 +112,9 @@ func Replace(w *bytes.Buffer, b []byte, from, to []Field) error {
if e != 0 { if e != 0 {
e++ e++
h.Write(b[s:e]) if _, err := h.Write(b[s:e]); err != nil {
return err
}
n, ok := tmap[h.Sum64()] n, ok := tmap[h.Sum64()]
h.Reset() h.Reset()

View File

@ -2,7 +2,6 @@ package jsn
import ( import (
"fmt" "fmt"
"reflect"
"strconv" "strconv"
"strings" "strings"
"unsafe" "unsafe"
@ -333,15 +332,6 @@ func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b)) return *(*string)(unsafe.Pointer(&b))
} }
func s2b(s string) []byte {
strh := (*reflect.StringHeader)(unsafe.Pointer(&s))
var sh reflect.SliceHeader
sh.Data = strh.Data
sh.Len = strh.Len
sh.Cap = strh.Len
return *(*[]byte)(unsafe.Pointer(&sh))
}
const maxStartEndStringLen = 80 const maxStartEndStringLen = 80
func startEndString(s string) string { func startEndString(s string) string {

View File

@ -244,7 +244,6 @@ func (m *Migrator) AppendMigration(name, upSQL, downSQL string) {
UpSQL: upSQL, UpSQL: upSQL,
DownSQL: downSQL, DownSQL: downSQL,
}) })
return
} }
// Migrate runs pending migrations // Migrate runs pending migrations
@ -315,7 +314,7 @@ func (m *Migrator) MigrateTo(targetVersion int32) (err error) {
if err != nil { if err != nil {
return err return err
} }
defer tx.Rollback(ctx) defer tx.Rollback(ctx) //nolint: errcheck
// Fire on start callback // Fire on start callback
if m.OnStart != nil { if m.OnStart != nil {
@ -332,7 +331,9 @@ func (m *Migrator) MigrateTo(targetVersion int32) (err error) {
} }
// Reset all database connection settings. Important to do before updating version as search_path may have been changed. // Reset all database connection settings. Important to do before updating version as search_path may have been changed.
tx.Exec(ctx, "reset all") if _, err := tx.Exec(ctx, "reset all"); err != nil {
return err
}
// Add one to the version // Add one to the version
_, err = tx.Exec(ctx, "update "+m.versionTable+" set version=$1", sequence) _, err = tx.Exec(ctx, "update "+m.versionTable+" set version=$1", sequence)

View File

@ -1,3 +1,4 @@
//nolint:errcheck
package psql package psql
import ( import (

View File

@ -27,8 +27,11 @@ func TestMain(m *testing.M) {
"token", "token",
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("user", "product", qcode.TRConfig{ err = qcompile.AddRole("user", "product", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Columns: []string{"id", "name", "price", "users", "customers"}, Columns: []string{"id", "name", "price", "users", "customers"},
Filters: []string{ Filters: []string{
@ -54,27 +57,39 @@ func TestMain(m *testing.M) {
}, },
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("anon", "product", qcode.TRConfig{ err = qcompile.AddRole("anon", "product", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Columns: []string{"id", "name"}, Columns: []string{"id", "name"},
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("anon1", "product", qcode.TRConfig{ err = qcompile.AddRole("anon1", "product", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Columns: []string{"id", "name", "price"}, Columns: []string{"id", "name", "price"},
DisableFunctions: true, DisableFunctions: true,
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("user", "users", qcode.TRConfig{ err = qcompile.AddRole("user", "users", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Columns: []string{"id", "full_name", "avatar", "email", "products"}, Columns: []string{"id", "full_name", "avatar", "email", "products"},
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("bad_dude", "users", qcode.TRConfig{ err = qcompile.AddRole("bad_dude", "users", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Filters: []string{"false"}, Filters: []string{"false"},
DisableFunctions: true, DisableFunctions: true,
@ -86,8 +101,11 @@ func TestMain(m *testing.M) {
Filters: []string{"false"}, Filters: []string{"false"},
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("user", "mes", qcode.TRConfig{ err = qcompile.AddRole("user", "mes", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Columns: []string{"id", "full_name", "avatar"}, Columns: []string{"id", "full_name", "avatar"},
Filters: []string{ Filters: []string{
@ -95,8 +113,11 @@ func TestMain(m *testing.M) {
}, },
}, },
}) })
if err != nil {
log.Fatal(err)
}
qcompile.AddRole("user", "customers", qcode.TRConfig{ err = qcompile.AddRole("user", "customers", qcode.TRConfig{
Query: qcode.QueryConfig{ Query: qcode.QueryConfig{
Columns: []string{"id", "email", "full_name", "products"}, Columns: []string{"id", "email", "full_name", "products"},
}, },
@ -167,7 +188,9 @@ func TestMain(m *testing.M) {
} }
for i, t := range tables { for i, t := range tables {
schema.updateSchema(t, columns[i], aliases) if err := schema.updateSchema(t, columns[i], aliases); err != nil {
log.Fatal(err)
}
} }
vars := NewVariables(map[string]string{ vars := NewVariables(map[string]string{

View File

@ -1,3 +1,4 @@
//nolint:errcheck
package psql package psql
import ( import (
@ -6,10 +7,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"math"
"strings" "strings"
"github.com/cespare/xxhash/v2"
"github.com/dosco/super-graph/qcode" "github.com/dosco/super-graph/qcode"
"github.com/dosco/super-graph/util" "github.com/dosco/super-graph/util"
) )
@ -249,7 +248,7 @@ func (c *compilerContext) renderSelect(sel *qcode.Select, ti *DBTableInfo) (uint
hasOrder := len(sel.OrderBy) != 0 hasOrder := len(sel.OrderBy) != 0
// SELECT // SELECT
if ti.Singular == false { if !ti.Singular {
//fmt.Fprintf(w, `SELECT coalesce(json_agg("%s"`, c.sel.Table) //fmt.Fprintf(w, `SELECT coalesce(json_agg("%s"`, c.sel.Table)
io.WriteString(c.w, `SELECT coalesce(json_agg("`) io.WriteString(c.w, `SELECT coalesce(json_agg("`)
io.WriteString(c.w, "json_") io.WriteString(c.w, "json_")
@ -351,7 +350,7 @@ func (c *compilerContext) renderSelectClose(sel *qcode.Select, ti *DBTableInfo)
io.WriteString(c.w, `') :: integer`) io.WriteString(c.w, `') :: integer`)
} }
if ti.Singular == false { if !ti.Singular {
//fmt.Fprintf(w, `) AS "json_agg_%d"`, c.sel.ID) //fmt.Fprintf(w, `) AS "json_agg_%d"`, c.sel.ID)
io.WriteString(c.w, `)`) io.WriteString(c.w, `)`)
aliasWithID(c.w, "json_agg", sel.ID) aliasWithID(c.w, "json_agg", sel.ID)
@ -417,7 +416,7 @@ func (c *compilerContext) renderColumns(sel *qcode.Select, ti *DBTableInfo) {
for _, col := range sel.Cols { for _, col := range sel.Cols {
n := funcPrefixLen(col.Name) n := funcPrefixLen(col.Name)
if n != 0 { if n != 0 {
if sel.Functions == false { if !sel.Functions {
continue continue
} }
if len(sel.Allowed) != 0 { if len(sel.Allowed) != 0 {
@ -956,7 +955,7 @@ func (c *compilerContext) renderOp(ex *qcode.Exp, sel *qcode.Select, ti *DBTable
if len(ti.TSVCol) == 0 { if len(ti.TSVCol) == 0 {
return fmt.Errorf("no tsv column defined for %s", ti.Name) return fmt.Errorf("no tsv column defined for %s", ti.Name)
} }
if col, ok = ti.Columns[ti.TSVCol]; !ok { if _, ok = ti.Columns[ti.TSVCol]; !ok {
return fmt.Errorf("no tsv column '%s' found ", ti.TSVCol) return fmt.Errorf("no tsv column '%s' found ", ti.TSVCol)
} }
//fmt.Fprintf(w, `(("%s") @@ to_tsquery('%s'))`, c.ti.TSVCol, val.Val) //fmt.Fprintf(w, `(("%s") @@ to_tsquery('%s'))`, c.ti.TSVCol, val.Val)
@ -1139,22 +1138,6 @@ func aliasWithIDSuffix(w io.Writer, alias string, id int32, suffix string) {
io.WriteString(w, `"`) io.WriteString(w, `"`)
} }
func colWithAlias(w io.Writer, col, alias string) {
io.WriteString(w, `"`)
io.WriteString(w, col)
io.WriteString(w, `" AS "`)
io.WriteString(w, alias)
io.WriteString(w, `"`)
}
func tableWithAlias(w io.Writer, table, alias string) {
io.WriteString(w, `"`)
io.WriteString(w, table)
io.WriteString(w, `" AS "`)
io.WriteString(w, alias)
io.WriteString(w, `"`)
}
func colWithTable(w io.Writer, table, col string) { func colWithTable(w io.Writer, table, col string) {
io.WriteString(w, `"`) io.WriteString(w, `"`)
io.WriteString(w, table) io.WriteString(w, table)
@ -1185,20 +1168,6 @@ func colWithTableIDAlias(w io.Writer, table string, id int32, col, alias string)
io.WriteString(w, `"`) io.WriteString(w, `"`)
} }
func colWithTableIDSuffixAlias(w io.Writer, table string, id int32,
suffix, col, alias string) {
io.WriteString(w, `"`)
io.WriteString(w, table)
io.WriteString(w, `_`)
int2string(w, id)
io.WriteString(w, suffix)
io.WriteString(w, `"."`)
io.WriteString(w, col)
io.WriteString(w, `" AS "`)
io.WriteString(w, alias)
io.WriteString(w, `"`)
}
func tableIDColSuffix(w io.Writer, table string, id int32, col, suffix string) { func tableIDColSuffix(w io.Writer, table string, id int32, col, suffix string) {
io.WriteString(w, `"`) io.WriteString(w, `"`)
io.WriteString(w, table) io.WriteString(w, table)
@ -1223,7 +1192,7 @@ func int2string(w io.Writer, val int32) {
for val2 > 0 { for val2 > 0 {
temp *= 10 temp *= 10
temp += val2 % 10 temp += val2 % 10
val2 = int32(math.Floor(float64(val2 / 10))) val2 = int32(float64(val2 / 10))
} }
val3 := temp val3 := temp
@ -1233,11 +1202,3 @@ func int2string(w io.Writer, val int32) {
w.Write([]byte{charset[d]}) w.Write([]byte{charset[d]})
} }
} }
func relID(h *xxhash.Digest, child, parent string) uint64 {
h.WriteString(child)
h.WriteString(parent)
v := h.Sum64()
h.Reset()
return v
}

View File

@ -199,7 +199,9 @@ func NewDBSchema(db *pgxpool.Pool, aliases map[string][]string) (*DBSchema, erro
return nil, err return nil, err
} }
schema.updateSchema(t, cols, aliases) if err := schema.updateSchema(t, cols, aliases); err != nil {
return nil, err
}
} }
return schema, nil return schema, nil
@ -208,7 +210,7 @@ func NewDBSchema(db *pgxpool.Pool, aliases map[string][]string) (*DBSchema, erro
func (s *DBSchema) updateSchema( func (s *DBSchema) updateSchema(
t *DBTable, t *DBTable,
cols []*DBColumn, cols []*DBColumn,
aliases map[string][]string) { aliases map[string][]string) error {
// Foreign key columns in current table // Foreign key columns in current table
colByID := make(map[int16]*DBColumn) colByID := make(map[int16]*DBColumn)
@ -281,12 +283,16 @@ func (s *DBSchema) updateSchema(
// Belongs-to relation between current table and the // Belongs-to relation between current table and the
// table in the foreign key // table in the foreign key
rel1 := &DBRel{RelBelongTo, "", "", c.Name, fc.Name} rel1 := &DBRel{RelBelongTo, "", "", c.Name, fc.Name}
s.SetRel(ct, ft, rel1) if err := s.SetRel(ct, ft, rel1); err != nil {
return err
}
// One-to-many relation between the foreign key table and the // One-to-many relation between the foreign key table and the
// the current table // the current table
rel2 := &DBRel{RelOneToMany, "", "", fc.Name, c.Name} rel2 := &DBRel{RelOneToMany, "", "", fc.Name, c.Name}
s.SetRel(ft, ct, rel2) if err := s.SetRel(ft, ct, rel2); err != nil {
return err
}
jcols = append(jcols, c) jcols = append(jcols, c)
} }
@ -301,42 +307,54 @@ func (s *DBSchema) updateSchema(
if len(jcols) > 1 { if len(jcols) > 1 {
for i := range jcols { for i := range jcols {
for n := range jcols { for n := range jcols {
if n != i { if n == i {
s.updateSchemaOTMT(ct, jcols[i], jcols[n], colByID) continue
}
err := s.updateSchemaOTMT(ct, jcols[i], jcols[n], colByID)
if err != nil {
return err
} }
} }
} }
} }
return nil
} }
func (s *DBSchema) updateSchemaOTMT( func (s *DBSchema) updateSchemaOTMT(
ct string, ct string,
col1, col2 *DBColumn, col1, col2 *DBColumn,
colByID map[int16]*DBColumn) { colByID map[int16]*DBColumn) error {
t1 := strings.ToLower(col1.FKeyTable) t1 := strings.ToLower(col1.FKeyTable)
t2 := strings.ToLower(col2.FKeyTable) t2 := strings.ToLower(col2.FKeyTable)
fc1, ok := colByID[col1.FKeyColID[0]] fc1, ok := colByID[col1.FKeyColID[0]]
if !ok { if !ok {
return return fmt.Errorf("expected column id '%d' not found", col1.FKeyColID[0])
} }
fc2, ok := colByID[col2.FKeyColID[0]] fc2, ok := colByID[col2.FKeyColID[0]]
if !ok { if !ok {
return return fmt.Errorf("expected column id '%d' not found", col2.FKeyColID[0])
} }
// One-to-many-through relation between 1nd foreign key table and the // One-to-many-through relation between 1nd foreign key table and the
// 2nd foreign key table // 2nd foreign key table
//rel1 := &DBRel{RelOneToManyThrough, ct, fc1.Name, col1.Name} //rel1 := &DBRel{RelOneToManyThrough, ct, fc1.Name, col1.Name}
rel1 := &DBRel{RelOneToManyThrough, ct, col2.Name, fc2.Name, col1.Name} rel1 := &DBRel{RelOneToManyThrough, ct, col2.Name, fc2.Name, col1.Name}
s.SetRel(t1, t2, rel1) if err := s.SetRel(t1, t2, rel1); err != nil {
return err
}
// One-to-many-through relation between 2nd foreign key table and the // One-to-many-through relation between 2nd foreign key table and the
// 1nd foreign key table // 1nd foreign key table
//rel2 := &DBRel{RelOneToManyThrough, ct, col2.Name, fc2.Name} //rel2 := &DBRel{RelOneToManyThrough, ct, col2.Name, fc2.Name}
rel2 := &DBRel{RelOneToManyThrough, ct, col1.Name, fc1.Name, col2.Name} rel2 := &DBRel{RelOneToManyThrough, ct, col1.Name, fc1.Name, col2.Name}
s.SetRel(t2, t1, rel2) if err := s.SetRel(t2, t1, rel2); err != nil {
return err
}
return nil
} }
func (s *DBSchema) GetTable(table string) (*DBTableInfo, error) { func (s *DBSchema) GetTable(table string) (*DBTableInfo, error) {

View File

@ -116,7 +116,7 @@ func listToMap(list []string) map[string]struct{} {
func mapToList(m map[string]string) []string { func mapToList(m map[string]string) []string {
list := []string{} list := []string{}
for k, _ := range m { for k := range m {
list = append(list, strings.ToLower(k)) list = append(list, strings.ToLower(k))
} }
sort.Strings(list) sort.Strings(list)

View File

@ -461,7 +461,7 @@ func (i *item) String() string {
case itemStringVal: case itemStringVal:
v = "string" v = "string"
} }
return fmt.Sprintf("%s", v) return v
} }
/* /*

View File

@ -85,7 +85,6 @@ type Parser struct {
input []byte // the string being scanned input []byte // the string being scanned
pos int pos int
items []item items []item
depth int
err error err error
} }
@ -185,15 +184,6 @@ func (p *Parser) ignore() {
p.pos = n p.pos = n
} }
func (p *Parser) current() item {
return p.items[p.pos]
}
func (p *Parser) eof() bool {
n := p.pos + 1
return p.items[n].typ == itemEOF
}
func (p *Parser) peek(types ...itemType) bool { func (p *Parser) peek(types ...itemType) bool {
n := p.pos + 1 n := p.pos + 1
if p.items[n].typ == itemEOF { if p.items[n].typ == itemEOF {
@ -250,7 +240,7 @@ func (p *Parser) parseOp() (*Operation, error) {
p.ignore() p.ignore()
for n := 0; n < 10; n++ { for n := 0; n < 10; n++ {
if p.peek(itemName) == false { if !p.peek(itemName) {
break break
} }
@ -275,7 +265,7 @@ func (p *Parser) parseQueryOp() (*Operation, error) {
var err error var err error
for n := 0; n < 10; n++ { for n := 0; n < 10; n++ {
if p.peek(itemName) == false { if !p.peek(itemName) {
break break
} }
@ -306,7 +296,7 @@ func (p *Parser) parseFields(fields []Field) ([]Field, error) {
continue continue
} }
if p.peek(itemName) == false { if !p.peek(itemName) {
return nil, errors.New("expecting an alias or field name") return nil, errors.New("expecting an alias or field name")
} }
@ -374,13 +364,13 @@ func (p *Parser) parseArgs(args []Arg) ([]Arg, error) {
p.ignore() p.ignore()
break break
} }
if p.peek(itemName) == false { if !p.peek(itemName) {
return nil, errors.New("expecting an argument name") return nil, errors.New("expecting an argument name")
} }
args = append(args, Arg{Name: p.val(p.next())}) args = append(args, Arg{Name: p.val(p.next())})
arg := &args[(len(args) - 1)] arg := &args[(len(args) - 1)]
if p.peek(itemColon) == false { if !p.peek(itemColon) {
return nil, errors.New("missing ':' after argument name") return nil, errors.New("missing ':' after argument name")
} }
p.ignore() p.ignore()
@ -441,12 +431,12 @@ func (p *Parser) parseObj() (*Node, error) {
break break
} }
if p.peek(itemName) == false { if !p.peek(itemName) {
return nil, errors.New("expecting an argument name") return nil, errors.New("expecting an argument name")
} }
nodeName := p.val(p.next()) nodeName := p.val(p.next())
if p.peek(itemColon) == false { if !p.peek(itemColon) {
return nil, errors.New("missing ':' after Field argument name") return nil, errors.New("missing ':' after Field argument name")
} }
p.ignore() p.ignore()

View File

@ -7,13 +7,16 @@ import (
func TestCompile1(t *testing.T) { func TestCompile1(t *testing.T) {
qc, _ := NewCompiler(Config{}) qc, _ := NewCompiler(Config{})
qc.AddRole("user", "product", TRConfig{ err := qc.AddRole("user", "product", TRConfig{
Query: QueryConfig{ Query: QueryConfig{
Columns: []string{"id", "Name"}, Columns: []string{"id", "Name"},
}, },
}) })
if err != nil {
t.Error(err)
}
_, err := qc.Compile([]byte(` _, err = qc.Compile([]byte(`
{ product(id: 15) { { product(id: 15) {
id id
name name
@ -26,13 +29,16 @@ func TestCompile1(t *testing.T) {
func TestCompile2(t *testing.T) { func TestCompile2(t *testing.T) {
qc, _ := NewCompiler(Config{}) qc, _ := NewCompiler(Config{})
qc.AddRole("user", "product", TRConfig{ err := qc.AddRole("user", "product", TRConfig{
Query: QueryConfig{ Query: QueryConfig{
Columns: []string{"ID"}, Columns: []string{"ID"},
}, },
}) })
if err != nil {
t.Error(err)
}
_, err := qc.Compile([]byte(` _, err = qc.Compile([]byte(`
query { product(id: 15) { query { product(id: 15) {
id id
name name
@ -45,13 +51,16 @@ func TestCompile2(t *testing.T) {
func TestCompile3(t *testing.T) { func TestCompile3(t *testing.T) {
qc, _ := NewCompiler(Config{}) qc, _ := NewCompiler(Config{})
qc.AddRole("user", "product", TRConfig{ err := qc.AddRole("user", "product", TRConfig{
Query: QueryConfig{ Query: QueryConfig{
Columns: []string{"ID"}, Columns: []string{"ID"},
}, },
}) })
if err != nil {
t.Error(err)
}
_, err := qc.Compile([]byte(` _, err = qc.Compile([]byte(`
mutation { mutation {
product(id: 15, name: "Test") { product(id: 15, name: "Test") {
id id

View File

@ -220,6 +220,8 @@ func (al *allowList) load() {
} }
func (al *allowList) save(item *allowItem) { func (al *allowList) save(item *allowItem) {
var err error
item.hash = gqlHash(item.gql, item.vars, "") item.hash = gqlHash(item.gql, item.vars, "")
item.name = gqlName(item.gql) item.name = gqlName(item.gql)
@ -271,22 +273,35 @@ func (al *allowList) save(item *allowItem) {
k := keys[i] k := keys[i]
v := urlMap[k] v := urlMap[k]
f.WriteString(fmt.Sprintf("# %s\n\n", k)) if _, err := f.WriteString(fmt.Sprintf("# %s\n\n", k)); err != nil {
logger.Error().Err(err).Send()
return
}
for i := range v { for i := range v {
if len(v[i].vars) != 0 && bytes.Equal(v[i].vars, []byte("{}")) == false { if len(v[i].vars) != 0 && !bytes.Equal(v[i].vars, []byte("{}")) {
vj, err := json.MarshalIndent(v[i].vars, "", "\t") vj, err := json.MarshalIndent(v[i].vars, "", "\t")
if err != nil { if err != nil {
logger.Warn().Err(err).Msg("Failed to write allow list 'vars' to file") logger.Warn().Err(err).Msg("Failed to write allow list 'vars' to file")
continue continue
} }
f.WriteString(fmt.Sprintf("variables %s\n\n", vj))
_, err = f.WriteString(fmt.Sprintf("variables %s\n\n", vj))
if err != nil {
logger.Error().Err(err).Send()
return
}
} }
if v[i].gql[0] == '{' { if v[i].gql[0] == '{' {
f.WriteString(fmt.Sprintf("query %s\n\n", v[i].gql)) _, err = f.WriteString(fmt.Sprintf("query %s\n\n", v[i].gql))
} else { } else {
f.WriteString(fmt.Sprintf("%s\n\n", v[i].gql)) _, err = f.WriteString(fmt.Sprintf("%s\n\n", v[i].gql))
}
if err != nil {
logger.Error().Err(err).Send()
return
} }
} }
} }

View File

@ -11,8 +11,7 @@ import (
const ( const (
authHeader = "Authorization" authHeader = "Authorization"
jwtBase int = iota jwtAuth0 int = iota + 1
jwtAuth0
) )
func jwtHandler(next http.HandlerFunc) http.HandlerFunc { func jwtHandler(next http.HandlerFunc) http.HandlerFunc {

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"os" "os"
"runtime"
"strings" "strings"
"github.com/dosco/super-graph/psql" "github.com/dosco/super-graph/psql"
@ -21,6 +22,14 @@ const (
serverName = "Super Graph" serverName = "Super Graph"
) )
var (
// These variables are set using -ldflags
version string
gitBranch string
lastCommitSHA string
lastCommitTime string
)
var ( var (
logger zerolog.Logger logger zerolog.Logger
errlog zerolog.Logger errlog zerolog.Logger
@ -133,6 +142,12 @@ e.g. db:migrate -+1
Run: cmdConfDump, Run: cmdConfDump,
}) })
rootCmd.AddCommand(&cobra.Command{
Use: "version",
Short: "Super Graph binary version information",
Run: cmdVersion,
})
rootCmd.Flags().StringVar(&confPath, rootCmd.Flags().StringVar(&confPath,
"path", "./config", "path to config files") "path", "./config", "path to config files")
@ -169,7 +184,10 @@ func initConf() (*config, error) {
} }
vi.SetConfigName(getConfigName()) vi.SetConfigName(getConfigName())
vi.MergeInConfig()
if err := vi.MergeInConfig(); err != nil {
return nil, err
}
} }
c := &config{} c := &config{}
@ -290,3 +308,28 @@ func initConfOnce() {
} }
} }
} }
func cmdVersion(cmd *cobra.Command, args []string) {
fmt.Printf("\n%s\n", BuildDetails())
}
func BuildDetails() string {
return fmt.Sprintf(`
Super Graph %v
Commit SHA-1 : %v
Commit timestamp : %v
Branch : %v
Go version : %v
For documentation, visit https://supergraph.dev
Licensed under the Apache Public License 2.0
Copyright 2015-2019 Vikram Rangnekar.
`,
version,
lastCommitSHA,
lastCommitTime,
gitBranch,
runtime.Version())
}

View File

@ -9,7 +9,7 @@ import (
func cmdConfDump(cmd *cobra.Command, args []string) { func cmdConfDump(cmd *cobra.Command, args []string) {
if len(args) != 1 { if len(args) != 1 {
cmd.Help() cmd.Help() //nolint: errcheck
os.Exit(1) os.Exit(1)
} }

View File

@ -14,19 +14,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var sampleMigration = `-- This is a sample migration.
create table users(
id serial primary key,
fullname varchar not null,
email varchar not null
);
---- create above / drop below ----
drop table users;
`
var newMigrationText = `-- Write your migrate up statements here var newMigrationText = `-- Write your migrate up statements here
---- create above / drop below ---- ---- create above / drop below ----
@ -48,7 +35,7 @@ func cmdDBSetup(cmd *cobra.Command, args []string) {
return return
} }
if os.IsNotExist(err) == false { if !os.IsNotExist(err) {
errlog.Fatal().Err(err).Msgf("unable to check if '%s' exists", sfile) errlog.Fatal().Err(err).Msgf("unable to check if '%s' exists", sfile)
} }
@ -108,7 +95,7 @@ func cmdDBDrop(cmd *cobra.Command, args []string) {
func cmdDBNew(cmd *cobra.Command, args []string) { func cmdDBNew(cmd *cobra.Command, args []string) {
if len(args) != 1 { if len(args) != 1 {
cmd.Help() cmd.Help() //nolint: errcheck
os.Exit(1) os.Exit(1)
} }
@ -142,7 +129,7 @@ func cmdDBNew(cmd *cobra.Command, args []string) {
func cmdDBMigrate(cmd *cobra.Command, args []string) { func cmdDBMigrate(cmd *cobra.Command, args []string) {
if len(args) == 0 { if len(args) == 0 {
cmd.Help() cmd.Help() //nolint: errcheck
os.Exit(1) os.Exit(1)
} }
@ -211,7 +198,7 @@ func cmdDBMigrate(cmd *cobra.Command, args []string) {
err = m.MigrateTo(currentVersion + mustParseDestination(dest[1:])) err = m.MigrateTo(currentVersion + mustParseDestination(dest[1:]))
} else { } else {
cmd.Help() cmd.Help() //nolint: errcheck
os.Exit(1) os.Exit(1)
} }

View File

@ -16,7 +16,7 @@ import (
func cmdNew(cmd *cobra.Command, args []string) { func cmdNew(cmd *cobra.Command, args []string) {
if len(args) != 1 { if len(args) != 1 {
cmd.Help() cmd.Help() //nolint: errcheck
os.Exit(1) os.Exit(1)
} }
@ -115,13 +115,17 @@ func (t *Templ) get(name string) ([]byte, error) {
b := bytes.Buffer{} b := bytes.Buffer{}
tmpl := fasttemplate.New(v, "{%", "%}") tmpl := fasttemplate.New(v, "{%", "%}")
tmpl.ExecuteFunc(&b, func(w io.Writer, tag string) (int, error) { _, err := tmpl.ExecuteFunc(&b, func(w io.Writer, tag string) (int, error) {
if val, ok := t.data[strings.TrimSpace(tag)]; ok { if val, ok := t.data[strings.TrimSpace(tag)]; ok {
return w.Write([]byte(val)) return w.Write([]byte(val))
} }
return 0, fmt.Errorf("unknown template variable '%s'", tag) return 0, fmt.Errorf("unknown template variable '%s'", tag)
}) })
if err != nil {
return nil, err
}
return b.Bytes(), nil return b.Bytes(), nil
} }
@ -133,7 +137,7 @@ func ifNotExists(filePath string, doFn func(string) error) {
return return
} }
if os.IsNotExist(err) == false { if !os.IsNotExist(err) {
errlog.Fatal().Err(err).Msgf("unable to check if '%s' exists", filePath) errlog.Fatal().Err(err).Msgf("unable to check if '%s' exists", filePath)
} }

View File

@ -43,7 +43,7 @@ func cmdDBSeed(cmd *cobra.Command, args []string) {
vm.Set("graphql", graphQLFunc) vm.Set("graphql", graphQLFunc)
console := vm.NewObject() console := vm.NewObject()
console.Set("log", logFunc) console.Set("log", logFunc) //nolint: errcheck
vm.Set("console", console) vm.Set("console", console)
fake := vm.NewObject() fake := vm.NewObject()
@ -100,7 +100,7 @@ func graphQLFunc(query string, data interface{}, opt map[string]string) map[stri
if err != nil { if err != nil {
errlog.Fatal().Err(err).Send() errlog.Fatal().Err(err).Send()
} }
defer tx.Rollback(c) defer tx.Rollback(c) //nolint: errcheck
if conf.DB.SetUserID { if conf.DB.SetUserID {
if err := setLocalUserID(c, tx); err != nil { if err := setLocalUserID(c, tx); err != nil {
@ -128,6 +128,7 @@ func graphQLFunc(query string, data interface{}, opt map[string]string) map[stri
return val return val
} }
//nolint: errcheck
func logFunc(args ...interface{}) { func logFunc(args ...interface{}) {
for _, arg := range args { for _, arg := range args {
if _, ok := arg.(map[string]interface{}); ok { if _, ok := arg.(map[string]interface{}); ok {
@ -144,6 +145,7 @@ func logFunc(args ...interface{}) {
} }
} }
//nolint: errcheck
func setFakeFuncs(f *goja.Object) { func setFakeFuncs(f *goja.Object) {
gofakeit.Seed(0) gofakeit.Seed(0)

View File

@ -173,9 +173,10 @@ func newConfig(name string) *viper.Viper {
vi.SetDefault("database.schema", "public") vi.SetDefault("database.schema", "public")
vi.SetDefault("env", "development") vi.SetDefault("env", "development")
vi.BindEnv("env", "GO_ENV")
vi.BindEnv("HOST", "HOST") vi.BindEnv("env", "GO_ENV") //nolint: errcheck
vi.BindEnv("PORT", "PORT") vi.BindEnv("HOST", "HOST") //nolint: errcheck
vi.BindEnv("PORT", "PORT") //nolint: errcheck
vi.SetDefault("auth.rails.max_idle", 80) vi.SetDefault("auth.rails.max_idle", 80)
vi.SetDefault("auth.rails.max_active", 12000) vi.SetDefault("auth.rails.max_active", 12000)

View File

@ -16,10 +16,6 @@ import (
"github.com/valyala/fasttemplate" "github.com/valyala/fasttemplate"
) )
const (
empty = ""
)
type coreContext struct { type coreContext struct {
req gqlReq req gqlReq
res gqlResp res gqlResp
@ -88,7 +84,7 @@ func (c *coreContext) resolvePreparedSQL() ([]byte, *stmt, error) {
if tx, err = db.Begin(c); err != nil { if tx, err = db.Begin(c); err != nil {
return nil, nil, err return nil, nil, err
} }
defer tx.Rollback(c) defer tx.Rollback(c) //nolint: errcheck
} }
if conf.DB.SetUserID { if conf.DB.SetUserID {
@ -173,7 +169,7 @@ func (c *coreContext) resolveSQL() ([]byte, *stmt, error) {
if tx, err = db.Begin(c); err != nil { if tx, err = db.Begin(c); err != nil {
return nil, nil, err return nil, nil, err
} }
defer tx.Rollback(c) defer tx.Rollback(c) //nolint: errcheck
} }
if conf.DB.SetUserID { if conf.DB.SetUserID {
@ -246,7 +242,7 @@ func (c *coreContext) resolveSQL() ([]byte, *stmt, error) {
} }
} }
if conf.Production == false { if !conf.Production {
_allowList.add(&c.req) _allowList.add(&c.req)
} }
@ -348,7 +344,7 @@ func parentFieldIds(h *xxhash.Digest, sel []qcode.Select, skipped uint32) (
for i := range sel { for i := range sel {
s := &sel[i] s := &sel[i]
if isSkipped(skipped, uint32(s.ID)) == false { if !isSkipped(skipped, uint32(s.ID)) {
continue continue
} }

View File

@ -59,9 +59,7 @@ func buildRoleStmt(gql, vars []byte, role string) ([]stmt, error) {
// For the 'anon' role in production only compile // For the 'anon' role in production only compile
// queries for tables defined in the config file. // queries for tables defined in the config file.
if conf.Production && if conf.Production && ro.Name == "anon" && !hasTablesWithConfig(qc, ro) {
ro.Name == "anon" &&
hasTablesWithConfig(qc, ro) == false {
return nil, errors.New("query contains tables with no 'anon' role config") return nil, errors.New("query contains tables with no 'anon' role config")
} }
@ -126,6 +124,7 @@ func buildMultiStmt(gql, vars []byte) ([]stmt, error) {
return stmts, nil return stmts, nil
} }
//nolint: errcheck
func renderUserQuery( func renderUserQuery(
stmts []stmt, vars map[string]json.RawMessage) (string, error) { stmts []stmt, vars map[string]json.RawMessage) (string, error) {

View File

@ -10,7 +10,7 @@ func TestFuzzCrashers(t *testing.T) {
} }
for _, f := range crashers { for _, f := range crashers {
gqlName(f) _ = gqlName(f)
gqlHash(f, nil, "") gqlHash(f, nil, "")
} }
} }

View File

@ -8,8 +8,6 @@ import (
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/gorilla/websocket"
) )
const ( const (
@ -20,7 +18,6 @@ const (
) )
var ( var (
upgrader = websocket.Upgrader{}
errUnauthorized = errors.New("not authorized") errUnauthorized = errors.New("not authorized")
) )
@ -33,8 +30,6 @@ type gqlReq struct {
hdr http.Header hdr http.Header
} }
type variables map[string]json.RawMessage
type gqlResp struct { type gqlResp struct {
Error string `json:"message,omitempty"` Error string `json:"message,omitempty"`
Data json.RawMessage `json:"data,omitempty"` Data json.RawMessage `json:"data,omitempty"`
@ -69,7 +64,8 @@ type resolver struct {
func apiv1Http(w http.ResponseWriter, r *http.Request) { func apiv1Http(w http.ResponseWriter, r *http.Request) {
ctx := &coreContext{Context: r.Context()} ctx := &coreContext{Context: r.Context()}
if conf.AuthFailBlock && authCheck(ctx) == false { //nolint: errcheck
if conf.AuthFailBlock && !authCheck(ctx) {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(gqlResp{Error: errUnauthorized.Error()}) json.NewEncoder(w).Encode(gqlResp{Error: errUnauthorized.Error()})
return return
@ -97,6 +93,7 @@ func apiv1Http(w http.ResponseWriter, r *http.Request) {
err = ctx.handleReq(w, r) err = ctx.handleReq(w, r)
//nolint: errcheck
if err == errUnauthorized { if err == errUnauthorized {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(gqlResp{Error: err.Error()}) json.NewEncoder(w).Encode(gqlResp{Error: err.Error()})
@ -110,6 +107,7 @@ func apiv1Http(w http.ResponseWriter, r *http.Request) {
} }
} }
//nolint: errcheck
func errorResp(w http.ResponseWriter, err error) { func errorResp(w http.ResponseWriter, err error) {
json.NewEncoder(w).Encode(gqlResp{Error: err.Error()}) json.NewEncoder(w).Encode(gqlResp{Error: err.Error()})
} }

View File

@ -2,6 +2,7 @@ package serv
import "net/http" import "net/http"
//nolint: errcheck
func introspect(w http.ResponseWriter) { func introspect(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{ w.Write([]byte(`{

View File

@ -30,7 +30,7 @@ func initPreparedList() {
if err != nil { if err != nil {
errlog.Fatal().Err(err).Send() errlog.Fatal().Err(err).Send()
} }
defer tx.Rollback(c) defer tx.Rollback(c) //nolint: errcheck
err = prepareRoleStmt(c, tx) err = prepareRoleStmt(c, tx)
if err != nil { if err != nil {
@ -74,7 +74,7 @@ func prepareStmt(c context.Context, gql string, vars []byte) error {
if err != nil { if err != nil {
return err return err
} }
defer tx.Rollback(c) defer tx.Rollback(c) //nolint: errcheck
switch qt { switch qt {
case qcode.QTQuery: case qcode.QTQuery:
@ -141,6 +141,7 @@ func prepare(c context.Context, tx pgx.Tx, st *stmt, key string) error {
return nil return nil
} }
// nolint: errcheck
func prepareRoleStmt(c context.Context, tx pgx.Tx) error { func prepareRoleStmt(c context.Context, tx pgx.Tx) error {
if len(conf.RolesQuery) == 0 { if len(conf.RolesQuery) == 0 {
return nil return nil

View File

@ -108,7 +108,7 @@ func Do(log func(string, ...interface{}), additional ...dir) error {
// Ensure that we use the correct events, as they are not uniform across // Ensure that we use the correct events, as they are not uniform across
// platforms. See https://github.com/fsnotify/fsnotify/issues/74 // platforms. See https://github.com/fsnotify/fsnotify/issues/74
if conf.Production == false && strings.HasSuffix(event.Name, "/allow.list") { if !conf.Production && strings.HasSuffix(event.Name, "/allow.list") {
continue continue
} }

345
serv/rice-box.go Normal file

File diff suppressed because one or more lines are too long

View File

@ -76,12 +76,16 @@ func initCompilers(c *config) (*qcode.Compiler, *psql.Compiler, error) {
delete.Filters = blockFilter delete.Filters = blockFilter
} }
qc.AddRole(r.Name, t.Name, qcode.TRConfig{ err := qc.AddRole(r.Name, t.Name, qcode.TRConfig{
Query: query, Query: query,
Insert: insert, Insert: insert,
Update: update, Update: update,
Delete: delete, Delete: delete,
}) })
if err != nil {
return nil, nil, err
}
} }
} }
@ -94,7 +98,7 @@ func initCompilers(c *config) (*qcode.Compiler, *psql.Compiler, error) {
} }
func initWatcher(cpath string) { func initWatcher(cpath string) {
if conf.WatchAndReload == false { if !conf.WatchAndReload {
return return
} }
@ -151,6 +155,8 @@ func startHTTP() {
}) })
logger.Info(). logger.Info().
Str("version", version).
Str("git_branch", gitBranch).
Str("host_post", hostPort). Str("host_post", hostPort).
Str("app_name", conf.AppName). Str("app_name", conf.AppName).
Str("env", conf.Env). Str("env", conf.Env).

View File

@ -12,6 +12,7 @@ import (
"github.com/dosco/super-graph/jsn" "github.com/dosco/super-graph/jsn"
) )
// nolint: errcheck
func mkkey(h *xxhash.Digest, k1 string, k2 string) uint64 { func mkkey(h *xxhash.Digest, k1 string, k2 string) uint64 {
h.WriteString(k1) h.WriteString(k1)
h.WriteString(k2) h.WriteString(k2)
@ -21,6 +22,7 @@ func mkkey(h *xxhash.Digest, k1 string, k2 string) uint64 {
return v return v
} }
// nolint: errcheck
func gqlHash(b string, vars []byte, role string) string { func gqlHash(b string, vars []byte, role string) string {
b = strings.TrimSpace(b) b = strings.TrimSpace(b)
h := sha1.New() h := sha1.New()
@ -64,7 +66,7 @@ func gqlHash(b string, vars []byte, role string) string {
} else { } else {
starting = false starting = false
s = e s = e
for e < len(b) && ws(b[e]) == false { for e < len(b) && !ws(b[e]) {
e++ e++
} }
if e != 0 { if e != 0 {
@ -81,7 +83,7 @@ func gqlHash(b string, vars []byte, role string) string {
io.WriteString(h, role) io.WriteString(h, role)
} }
if vars == nil || len(vars) == 0 { if len(vars) == 0 {
return hex.EncodeToString(h.Sum(nil)) return hex.EncodeToString(h.Sum(nil))
} }