├── .github
└── workflows
│ ├── bump-test.yml
│ └── release.yml
├── .gitignore
├── .goreleaser.linux.yaml
├── .goreleaser.mac.yaml
├── .goreleaser.windows.yaml
├── .infisical.json
├── LICENSE
├── README.md
├── dbrest.go
├── dbrest_cli.go
├── docker
└── Dockerfile
├── env
└── env.go
├── go.mod
├── go.sum
├── scripts
└── prep.gomod.sh
├── server
├── request.go
├── response.go
├── routes.go
├── routes_connection.go
├── routes_query.go
├── routes_table.go
├── server.go
├── server_functions.go
└── server_test.go
└── state
├── grants.go
├── project.go
├── project_tokens.go
├── query.go
├── roles.go
├── state.go
└── version.go
/.github/workflows/bump-test.yml:
--------------------------------------------------------------------------------
1 | name: Bump & Test
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 |
7 | jobs:
8 | bump:
9 | if: "! contains(github.event.head_commit.message, '[skip ci]')"
10 | runs-on: ubuntu-latest
11 | outputs:
12 | new_tag: ${{ steps.tag_version.outputs.new_tag }}
13 | new_version: ${{ steps.tag_version.outputs.new_version }}
14 | steps:
15 | - uses: actions/checkout@v2
16 | - name: Bump version and push tag
17 | id: tag_version
18 | uses: mathieudutour/github-tag-action@v6.0
19 | with:
20 | github_token: ${{ secrets.GITHUB_TOKEN }}
21 | custom_tag: ${{ github.event.inputs.tag }}
22 |
23 | test:
24 | if: "! (contains(github.event.head_commit.message, '[skip ci]') || contains(github.event.head_commit.message, '[no test]') || contains(github.event.head_commit.message, '[bump]'))"
25 |
26 | needs: [bump]
27 |
28 | runs-on: 'ubuntu-latest'
29 | timeout-minutes: 10
30 |
31 | steps:
32 | - uses: actions/checkout@v2
33 |
34 | - name: Set up GoLang
35 | uses: actions/setup-go@v3
36 | with:
37 | go-version: "1.22"
38 | cache: true
39 |
40 | - name: Run Go Tests
41 | run: |
42 | bash scripts/prep.gomod.sh
43 |
44 | go mod tidy
45 | go build .
46 |
47 | cd server
48 | go test -run TestServer
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Build & Release
2 |
3 | on:
4 | workflow_dispatch:
5 |
6 | jobs:
7 |
8 | release-brew:
9 | timeout-minutes: 15
10 | # runs-on: [self-hosted, macOS, ARM64]
11 | runs-on: macos-latest
12 |
13 | steps:
14 | - name: Checkout
15 | uses: actions/checkout@v1
16 | with:
17 | fetch-depth: 0
18 |
19 | - name: Set up Go
20 | uses: actions/setup-go@v3
21 | with:
22 | go-version: "1.22"
23 | cache: true
24 |
25 | - name: Run GoReleaser
26 | uses: goreleaser/goreleaser-action@v3
27 | with:
28 | distribution: goreleaser
29 | version: 'v1.26.2'
30 | args: release --clean --skip-validate -f .goreleaser.mac.yaml
31 | env:
32 | GITHUB_TOKEN: ${{ secrets.REPO_GITHUB_TOKEN }}
33 | RUDDERSTACK_URL: ${{ secrets.RUDDERSTACK_URL }}
34 |
35 | release-scoop:
36 | # runs-on: [self-hosted, Windows]
37 | runs-on: windows-latest
38 | timeout-minutes: 15
39 |
40 | steps:
41 | - name: Checkout
42 | uses: actions/checkout@v3
43 | with:
44 | fetch-depth: 0
45 |
46 | - name: Set up Go
47 | uses: actions/setup-go@v3
48 | with:
49 | go-version: "1.22"
50 | cache: true
51 |
52 | - name: Run GoReleaser
53 | # uses: flarco/goreleaser-action@master
54 | uses: goreleaser/goreleaser-action@v3
55 | with:
56 | distribution: goreleaser
57 | version: 'v1.26.2'
58 | args: release --clean --skip-validate -f .goreleaser.windows.yaml
59 | env:
60 | GITHUB_TOKEN: ${{ secrets.REPO_GITHUB_TOKEN }}
61 | RUDDERSTACK_URL: ${{ secrets.RUDDERSTACK_URL }}
62 |
63 | release-linux:
64 | runs-on: ubuntu-latest
65 | # runs-on: [self-hosted, Linux]
66 | timeout-minutes: 15
67 |
68 | steps:
69 | - name: Checkout
70 | uses: actions/checkout@v3
71 | with:
72 | fetch-depth: 0
73 |
74 | - name: Set up Go
75 | uses: actions/setup-go@v3
76 | with:
77 | go-version: "1.22"
78 | cache: true
79 |
80 | - name: Login docker
81 | env:
82 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
83 | run: |
84 | echo "$DOCKER_PASSWORD" | docker login -u dbrest --password-stdin
85 |
86 | - name: Run GoReleaser
87 | # uses: flarco/goreleaser-action@master
88 | uses: goreleaser/goreleaser-action@v3
89 | with:
90 | distribution: goreleaser
91 | version: 'v1.26.2'
92 | args: release --clean --skip-validate -f .goreleaser.linux.yaml
93 | env:
94 | GITHUB_TOKEN: ${{ secrets.REPO_GITHUB_TOKEN }}
95 | RUDDERSTACK_URL: ${{ secrets.RUDDERSTACK_URL }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, built with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | # Dependency directories (remove the comment below to include it)
15 | # vendor/
16 | dist/
17 | dbrest
18 | server/test
19 |
--------------------------------------------------------------------------------
/.goreleaser.linux.yaml:
--------------------------------------------------------------------------------
1 | # This is an example .goreleaser.yml file with some sensible defaults.
2 | # Make sure to check the documentation at https://goreleaser.com
3 | project_name: dbrest
4 |
5 | before:
6 | hooks:
7 | - go mod edit -dropreplace='github.com/flarco/g' go.mod
8 | - go mod edit -dropreplace='github.com/slingdata-io/sling-cli' go.mod
9 | - go mod edit -droprequire='github.com/slingdata-io/sling' go.mod
10 | - go mod tidy
11 |
12 | builds:
13 | - main: .
14 |
15 | env:
16 | - CGO_ENABLED=1
17 |
18 | goarch:
19 | - amd64
20 | # - '386'
21 | # - arm64
22 | # - arm
23 | # goarm:
24 | # - '6'
25 | # - '7'
26 | goos:
27 | - linux
28 | ldflags:
29 | - "-X 'github.com/dbrest-io/dbrest/state.Version={{ .Version }}' -X 'github.com/dbrest-io/dbrest/state.RudderstackURL={{ .Env.RUDDERSTACK_URL }}'"
30 |
31 | archives:
32 | - name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ with .Mips }}_{{ . }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
33 |
34 | checksum:
35 | name_template: "{{ .ProjectName }}_{{ .Runtime.Goos }}_{{ .Runtime.Goarch }}_checksums.txt"
36 |
37 | snapshot:
38 | name_template: "{{ incpatch .Version }}"
39 |
40 | dockers:
41 | - dockerfile: 'docker/Dockerfile'
42 | image_templates:
43 | - "dbrest/dbrest:latest"
44 | - "dbrest/dbrest:{{ .Tag }}"
45 |
46 | release:
47 | mode: replace
48 | header: |
49 | ## dbREST {{ .Tag }} ({{ .Date }})
50 |
51 |
--------------------------------------------------------------------------------
/.goreleaser.mac.yaml:
--------------------------------------------------------------------------------
1 | # This is an example .goreleaser.yml file with some sensible defaults.
2 | # Make sure to check the documentation at https://goreleaser.com
3 | project_name: dbrest
4 |
5 | before:
6 | hooks:
7 | - go mod edit -dropreplace='github.com/flarco/g' go.mod
8 | - go mod edit -dropreplace='github.com/slingdata-io/sling-cli' go.mod
9 | - go mod edit -droprequire='github.com/slingdata-io/sling' go.mod
10 | - go mod tidy
11 |
12 | builds:
13 | - main: .
14 |
15 | env:
16 | - CGO_ENABLED=1
17 |
18 | goarch:
19 | - amd64
20 | - arm64
21 | goos:
22 | # - linux
23 | # - windows
24 | - darwin
25 | ldflags:
26 | - "-X 'github.com/dbrest-io/dbrest/state.Version={{ .Version }}' -X 'github.com/dbrest-io/dbrest/state.RudderstackURL={{ .Env.RUDDERSTACK_URL }}'"
27 |
28 | universal_binaries:
29 | - id: dbrest
30 | replace: false
31 |
32 | archives:
33 | - name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ with .Mips }}_{{ . }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
34 |
35 | checksum:
36 | name_template: "{{ .ProjectName }}_{{ .Runtime.Goos }}_{{ .Runtime.Goarch }}_checksums.txt"
37 |
38 | snapshot:
39 | name_template: "{{ incpatch .Version }}"
40 |
41 | release:
42 | mode: replace
43 | header: |
44 | ## dbREST {{ .Tag }} ({{ .Date }})
45 |
46 | brews:
47 | - name: dbrest
48 | repository:
49 | owner: dbrest-io
50 | name: homebrew-dbrest
51 | branch: main
52 |
53 | homepage: https:/github.com/dbrest-io/dbrest
54 |
55 | description: "dbREST is an API backend that you can put in front of your database. Ever wanted to spin up an API service in front of your Snowflake, MySQL or even SQLite database? Well, dbREST allows that!"
--------------------------------------------------------------------------------
/.goreleaser.windows.yaml:
--------------------------------------------------------------------------------
1 | # This is an example .goreleaser.yml file with some sensible defaults.
2 | # Make sure to check the documentation at https://goreleaser.com
3 | project_name: dbrest
4 |
5 | before:
6 | hooks:
7 | - go mod edit -dropreplace='github.com/flarco/g' go.mod
8 | - go mod edit -dropreplace='github.com/slingdata-io/sling-cli' go.mod
9 | - go mod edit -droprequire='github.com/slingdata-io/sling' go.mod
10 | - go mod tidy
11 |
12 | builds:
13 | - main: .
14 |
15 | env:
16 | - CGO_ENABLED=1
17 |
18 | goarch:
19 | - amd64
20 | # - arm64
21 | goos:
22 | - windows
23 | ldflags:
24 | - "-X 'github.com/dbrest-io/dbrest/state.Version={{ .Version }}' -X 'github.com/dbrest-io/dbrest/state.RudderstackURL={{ .Env.RUDDERSTACK_URL }}'"
25 |
26 | archives:
27 | - name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ with .Mips }}_{{ . }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
28 |
29 | checksum:
30 | name_template: "{{ .ProjectName }}_{{ .Runtime.Goos }}_{{ .Runtime.Goarch }}_checksums.txt"
31 |
32 | snapshot:
33 | name_template: "{{ incpatch .Version }}"
34 |
35 | release:
36 | mode: replace
37 | header: |
38 | ## dbREST {{ .Tag }} ({{ .Date }})
39 |
40 | scoops:
41 | - name: dbrest
42 | repository:
43 | owner: dbrest-io
44 | name: scoop-dbrest
45 | branch: main
46 |
47 | homepage: https:/github.com/dbrest-io/dbrest
48 |
49 | description: "dbREST is an API backend that you can put in front of your database. Ever wanted to spin up an API service in front of your Snowflake, MySQL or even SQLite database? Well, dbREST allows that!"
--------------------------------------------------------------------------------
/.infisical.json:
--------------------------------------------------------------------------------
1 | {
2 | "workspaceId": "de677db3-316b-48ff-8eec-22ffe81262cb",
3 | "defaultEnvironment": "",
4 | "gitBranchToEnvironmentMapping": null
5 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | dbREST is basically an API backend that you can put in front of your database. Ever wanted to spin up an API service in front of your Snowflake, MySQL or even SQLite database? Well, dbREST allows that! See https://docs.dbrest.io for more details.
7 |
8 | Running `dbrest serve` will launch an API process which allow you to:
9 |
10 |
11 | Select a table's data
12 |
13 | ```http
14 | GET /snowflake_db/my_schema/docker_logs?.columns=container_name,timestamp&.limit=100
15 | ```
16 |
17 | ```json
18 | [
19 | { "container_name": "vector", "timestamp": "2022-04-22T23:54:06.644268688Z" },
20 | { "container_name": "postgres", "timestamp": "2022-04-22T23:54:06.644315426Z" },
21 | { "container_name": "api", "timestamp": "2022-04-22T23:54:06.654821046Z" },
22 | ]
23 | ```
24 |
25 |
26 | Insert into a table
27 |
28 | ```http
29 | POST /snowflake_db/my_schema/docker_logs
30 |
31 | [
32 | {"container_name":"vector","host":"vector","image":"timberio/vector:0.21.1-debian","message":"2022-04-22T23:54:06.644214Z INFO vector::sources::docker_logs: Capturing logs from now on. now=2022-04-22T23:54:06.644150817+00:00","stream":"stderr","timestamp":"2022-04-22T23:54:06.644268688Z"}
33 | ]
34 | ```
35 |
36 |
37 | Update a table
38 |
39 | ```http
40 | PATCH /snowflake_db/my_schema/my_table?.key=col1
41 |
42 | [
43 | { "col1": "123", "timestamp": "2022-04-22T23:54:06.644268688Z" },
44 | { "col1": "124", "timestamp": "2022-04-22T23:54:06.644315426Z" },
45 | { "col1": "125", "timestamp": "2022-04-22T23:54:06.654821046Z" }
46 | ]
47 | ```
48 |
49 |
50 | Upsert into a table
51 |
52 | ```http
53 | PUT /snowflake_db/my_schema/my_table?.key=col1
54 |
55 | [
56 | { "col1": "123", "timestamp": "2022-04-22T23:54:06.644268688Z" },
57 | { "col1": "124", "timestamp": "2022-04-22T23:54:06.644315426Z" },
58 | { "col1": "125", "timestamp": "2022-04-22T23:54:06.654821046Z" }
59 | ]
60 | ```
61 |
62 |
63 | Submit a Custom SQL query
64 |
65 | ```http
66 | POST /snowflake_db/.sql
67 |
68 | select * from my_schema.docker_logs where timestamp is not null
69 | ```
70 |
71 | ```json
72 | [
73 | { "container_name": "vector", "timestamp": "2022-04-22T23:54:06.644268688Z" },
74 | { "container_name": "postgres", "timestamp": "2022-04-22T23:54:06.644315426Z" },
75 | { "container_name": "api", "timestamp": "2022-04-22T23:54:06.654821046Z" },
76 | ]
77 | ```
78 |
79 |
80 | List all columns in a table
81 |
82 | ```http
83 | GET /snowflake_db/my_schema/docker_logs/.columns
84 | ```
85 |
86 | ```json
87 | [
88 | {"column_id":1,"column_name":"timestamp", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},
89 | {"column_id":2,"column_name":"container_name", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},
90 | {"column_id":3,"column_name":"host", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},{"column_id":4,"column_name":"image", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},
91 | ]
92 | ```
93 |
94 |
95 | List all tables in a schema
96 |
97 | ```http
98 | GET /snowflake_db/my_schema/.tables
99 | ```
100 |
101 | ```json
102 | [
103 | {"database_name":"default", "is_view":"table", "schema_name":"my_schema", "table_name":"docker_logs"},
104 | {"database_name":"default", "is_view":"table", "schema_name":"my_schema", "table_name":"example"},
105 | {"database_name":"default", "is_view":"view", "schema_name":"my_schema", "table_name":"place_vw"}
106 | ]
107 | ```
108 |
109 |
110 |
111 | List all columns, in all tables in a schema
112 |
113 | ```http
114 | GET /snowflake_db/my_schema/.columns
115 | ```
116 |
117 | ```json
118 | [
119 | {"column_id":1,"column_name":"timestamp", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},
120 | {"column_id":2,"column_name":"container_name", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},
121 | {"column_id":3,"column_name":"host", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},{"column_id":4,"column_name":"image", "column_type":"String", "database_name":"default", "schema_name":"my_schema", "table_name":"docker_logs", "table_type":"table"},
122 | ]
123 | ```
124 |
125 |
126 | Of course there must be an authentication / authorization logic. It is based on tokens being issued with the `dbrest tokens` sub-command which are tied to roles defined in a YAML config file:
127 |
128 | ```yaml
129 | reader:
130 | snowflake_db:
131 | allow_read:
132 | - schema1.*
133 | - schema2.table1
134 | allow_sql: 'disable'
135 |
136 | my_pg:
137 | allow_read:
138 | - '*'
139 | allow_sql: 'disable'
140 |
141 | writer:
142 | snowflake_db:
143 | allow_read:
144 | - schema1.*
145 | - schema2.table1
146 | allow_write:
147 | - schema2.table3
148 | allow_sql: 'disable'
149 |
150 | my_pg:
151 | allow_read:
152 | - '*'
153 | allow_write:
154 | - '*'
155 | allow_sql: 'any'
156 | ```
157 |
158 | We can now issue tokens with `dbrest tokens issue --roles reader,writer`.
159 |
160 | It is built in Go. And as you might have guessed, it also powers alot of [`dbNet`](https://github.com/dbnet-io/dbnet) :).
161 |
162 | dbREST is in active developement. Here are some of the databases it connects to:
163 | * Clickhouse
164 | * Google BigQuery
165 | * Google BigTable
166 | * MySQL
167 | * Oracle
168 | * Redshift
169 | * PostgreSQL
170 | * SQLite
171 | * SQL Server
172 | * Snowflake
173 | * DuckDB
174 | * ScyllaDB (coming soon)
175 | * Firebolt (coming soon)
176 | * Databricks (coming soon)
177 |
178 | # Running it locally
179 |
180 | ## Brew (Mac)
181 |
182 | ```bash
183 | brew install dbrest-io/dbrest/dbrest
184 |
185 | # You're good to go!
186 | dbrest -h
187 | ```
188 | ## Scoop (Windows)
189 |
190 | ```bash
191 | scoop bucket add dbrest https://github.com/dbrest-io/scoop-dbrest.git
192 | scoop install dbrest
193 |
194 | # You're good to go!
195 | dbrest -h
196 | ```
197 | ## Docker
198 |
199 | ```bash
200 | docker run --rm -it dbrest/dbrest -h
201 | ```
202 |
203 | ## Binary (Linux)
204 |
205 | ```bash
206 | # Download binary (amd64)
207 | curl -LO 'https://github.com/dbrest-io/dbREST/releases/latest/download/dbrest_linux_amd64.tar.gz' \
208 | && tar xf dbrest_linux_amd64.tar.gz \
209 | && rm -f dbrest_linux_amd64.tar.gz \
210 | && chmod +x dbrest
211 |
212 | # You're good to go!
213 | ./dbrest -h
214 | ```
215 |
216 | ## From Source
217 |
218 | ```bash
219 | git clone https://github.com/dbrest-io/dbREST.git
220 | cd dbREST
221 | go mod tidy # get all dependencies
222 | go build -o dbrest
223 | ```
224 |
--------------------------------------------------------------------------------
/dbrest.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "os"
6 | "os/signal"
7 | "syscall"
8 | "time"
9 |
10 | "github.com/flarco/g"
11 | )
12 |
13 | var ctx = g.NewContext(context.Background())
14 | var interrupted = false
15 |
16 | func main() {
17 |
18 | exitCode := 11
19 | done := make(chan struct{})
20 | interrupt := make(chan os.Signal, 1)
21 | kill := make(chan os.Signal, 1)
22 | signal.Notify(interrupt, os.Interrupt)
23 | signal.Notify(kill, syscall.SIGTERM)
24 |
25 | go func() {
26 | defer close(done)
27 | exitCode = cliInit()
28 | }()
29 |
30 | select {
31 | case <-done:
32 | os.Exit(exitCode)
33 | case <-kill:
34 | println("\nkilling process...")
35 | os.Exit(111)
36 | case <-interrupt:
37 | if cliServe.Sc.Used {
38 | println("\ninterrupting...")
39 | interrupted = true
40 |
41 | ctx.Cancel()
42 |
43 | select {
44 | case <-done:
45 | case <-time.After(5 * time.Second):
46 | }
47 | }
48 | os.Exit(exitCode)
49 | return
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/dbrest_cli.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "runtime"
7 | "sort"
8 | "strings"
9 |
10 | "github.com/dbrest-io/dbrest/env"
11 | "github.com/dbrest-io/dbrest/server"
12 | "github.com/dbrest-io/dbrest/state"
13 | "github.com/denisbrodbeck/machineid"
14 | "github.com/flarco/g"
15 | "github.com/flarco/g/net"
16 | "github.com/integrii/flaggy"
17 | "github.com/jedib0t/go-pretty/table"
18 | "github.com/kardianos/osext"
19 | "github.com/samber/lo"
20 | "github.com/slingdata-io/sling-cli/core/dbio/connection"
21 | "github.com/slingdata-io/sling-cli/core/dbio/iop"
22 | "github.com/spf13/cast"
23 | )
24 |
25 | var cliServe = &g.CliSC{
26 | Name: "serve",
27 | Description: "launch the dbREST API endpoint",
28 | ExecProcess: serve,
29 | }
30 |
31 | var cliConns = &g.CliSC{
32 | Name: "conns",
33 | Singular: "local connection",
34 | Description: "Manage local connections in the dbREST env file",
35 | SubComs: []*g.CliSC{
36 | {
37 | Name: "list",
38 | Description: "list local connections detected",
39 | },
40 | {
41 | Name: "test",
42 | Description: "test a local connection",
43 | PosFlags: []g.Flag{
44 | {
45 | Name: "name",
46 | ShortName: "",
47 | Type: "string",
48 | Description: "The name of the connection to test",
49 | },
50 | },
51 | },
52 | {
53 | Name: "unset",
54 | Description: "remove a connection from the dbREST env file",
55 | PosFlags: []g.Flag{
56 | {
57 | Name: "name",
58 | ShortName: "",
59 | Type: "string",
60 | Description: "The name of the connection to remove",
61 | },
62 | },
63 | },
64 | {
65 | Name: "set",
66 | Description: "set a connection in the dbREST env file",
67 | PosFlags: []g.Flag{
68 | {
69 | Name: "name",
70 | ShortName: "",
71 | Type: "string",
72 | Description: "The name of the connection to set",
73 | },
74 | {
75 | Name: "key=value properties...",
76 | ShortName: "",
77 | Type: "string",
78 | Description: "The key=value properties to set. See https://docs.dbrest.io/",
79 | },
80 | },
81 | },
82 | },
83 | ExecProcess: conns,
84 | }
85 |
86 | var cliTokens = &g.CliSC{
87 | Name: "tokens",
88 | Description: "manage access tokens & roles",
89 | SubComs: []*g.CliSC{
90 | {
91 | Name: "issue",
92 | Description: "create or replace a token. If it exists, add --regenerate to regenerate it.",
93 | PosFlags: []g.Flag{
94 | {
95 | Name: "name",
96 | ShortName: "",
97 | Type: "string",
98 | Description: "The name of the token",
99 | },
100 | },
101 | Flags: []g.Flag{
102 | {
103 | Name: "roles",
104 | Type: "string",
105 | Description: "The roles to attach the token to",
106 | },
107 | {
108 | Name: "regenerate",
109 | Type: "bool",
110 | Description: "Whether to regenerate the token value (if it exists)",
111 | },
112 | },
113 | },
114 | {
115 | Name: "revoke",
116 | Description: "delete an existing token. The token will no longer have access to the API",
117 | PosFlags: []g.Flag{
118 | {
119 | Name: "name",
120 | ShortName: "",
121 | Type: "string",
122 | Description: "The name of the token",
123 | },
124 | },
125 | },
126 | {
127 | Name: "toggle",
128 | Description: "Enable/Disable a token",
129 | PosFlags: []g.Flag{
130 | {
131 | Name: "name",
132 | ShortName: "",
133 | Type: "string",
134 | Description: "The name of the token",
135 | },
136 | },
137 | },
138 | {
139 | Name: "list",
140 | Description: "List all existing tokens",
141 | },
142 | {
143 | Name: "roles",
144 | Description: "List all roles detected in " + state.DefaultProject().RolesFile,
145 | },
146 | },
147 | ExecProcess: tokens,
148 | }
149 |
150 | func serve(c *g.CliSC) (ok bool, err error) {
151 | project := state.DefaultProject()
152 | if len(project.Connections) == 0 {
153 | g.Warn("No connections have been defined. Please create some with command `dbrest conns` or put a URL in an environment variable. See https://docs.dbrest.io for more details.")
154 | return true, g.Error("No connections have been defined. Please create file %s", project.Directory)
155 | } else if !g.PathExists(project.RolesFile) {
156 | g.Warn("No roles have been defined. See https://docs.dbrest.io for more details.")
157 | return true, g.Error("No roles have been defined. Please create file %s", project.RolesFile)
158 | } else if !g.PathExists(project.TokenFile) {
159 | g.Warn("No tokens have been issued. Please issue with command `dbrest token`. See https://docs.dbrest.io for more details.")
160 | }
161 |
162 | s := server.NewServer()
163 | defer s.Close()
164 |
165 | go s.Start()
166 | go telemetry("serve")
167 | go checkVersion()
168 |
169 | <-ctx.Ctx.Done()
170 |
171 | return true, nil
172 | }
173 |
174 | func conns(c *g.CliSC) (ok bool, err error) {
175 | ok = true
176 |
177 | entries := connection.GetLocalConns()
178 | ef := env.LoadDbRestEnvFile(state.DefaultProject().EnvFile)
179 | ec := connection.EnvFileConns{EnvFile: &ef}
180 |
181 | switch c.UsedSC() {
182 | case "unset":
183 | name := strings.ToLower(cast.ToString(c.Vals["name"]))
184 | if name == "" {
185 | flaggy.ShowHelp("")
186 | return ok, nil
187 | }
188 |
189 | err := ec.Unset(name)
190 | if err != nil {
191 | return ok, g.Error(err, "could not unset %s", name)
192 | }
193 | g.Info("connection `%s` has been removed from %s", name, ec.EnvFile.Path)
194 | case "set":
195 | if len(c.Vals) == 0 {
196 | flaggy.ShowHelp("")
197 | return ok, nil
198 | }
199 |
200 | kvArr := []string{cast.ToString(c.Vals["value properties..."])}
201 | kvMap := map[string]interface{}{}
202 | for k, v := range g.KVArrToMap(append(kvArr, flaggy.TrailingArguments...)...) {
203 | k = strings.ToLower(k)
204 | kvMap[k] = v
205 | }
206 | name := strings.ToLower(cast.ToString(c.Vals["name"]))
207 |
208 | err := ec.Set(name, kvMap)
209 | if err != nil {
210 | return ok, g.Error(err, "could not unset %s", name)
211 | }
212 | g.Info("connection `%s` has been set in %s. Please test with `dbrest conns test %s`", name, ec.EnvFile.Path, name)
213 |
214 | case "list":
215 | fields, rows := entries.List()
216 | fmt.Println(g.PrettyTable(fields, rows))
217 |
218 | case "test":
219 | name := cast.ToString(c.Vals["name"])
220 | ok, err = entries.Test(name)
221 | if err != nil {
222 | return ok, g.Error(err, "could not test %s", name)
223 | } else if ok {
224 | g.Info("success!") // successfully connected
225 | }
226 |
227 | default:
228 | return false, nil
229 | }
230 | return ok, nil
231 | }
232 |
233 | func tokens(c *g.CliSC) (ok bool, err error) {
234 | ok = true
235 | name := strings.ToLower(cast.ToString(c.Vals["name"]))
236 | roles := strings.Split(cast.ToString(c.Vals["roles"]), ",")
237 | project := state.DefaultProject()
238 |
239 | switch c.UsedSC() {
240 | case "issue":
241 | if name == "" {
242 | return false, nil
243 | } else if len(roles) == 0 || roles[0] == "" {
244 | g.Warn("Must provide roles with --roles")
245 | return false, nil
246 | }
247 |
248 | regenerate := cast.ToBool(c.Vals["regenerate"])
249 | token := state.NewToken(roles)
250 | oldToken, existing := project.Tokens[name]
251 | if existing {
252 | if !regenerate {
253 | token.Token = oldToken.Token
254 | }
255 | }
256 |
257 | err = project.TokenAdd(name, token)
258 | if err != nil {
259 | return ok, g.Error(err, "could not issue token")
260 | }
261 | if !existing || regenerate {
262 | if regenerate {
263 | g.Info("Successfully regenerated token `%s`", name)
264 | } else {
265 | g.Info("Successfully added token `%s`", name)
266 | }
267 | g.Info("Token Value is: " + token.Token)
268 | } else {
269 | g.Info("Successfully updated roles for token `%s`. The token value was unchanged. Use --regenerate to regenerate token value.", name)
270 | }
271 | case "revoke":
272 | if name == "" {
273 | return false, nil
274 | }
275 | err = project.TokenRemove(name)
276 | if err != nil {
277 | return ok, g.Error(err, "could not revoke token")
278 | }
279 | g.Info("Successfully removed token `%s`", name)
280 | case "toggle":
281 | if name == "" {
282 | return false, nil
283 | }
284 | disabled, err := project.TokenToggle(name)
285 | if err != nil {
286 | return ok, g.Error(err, "could not toggle token")
287 | }
288 | g.Info("token `%s` is now %s", name, lo.Ternary(disabled, "disabled", "enabled"))
289 | case "list":
290 | tokens := lo.Keys(project.Tokens)
291 | sort.Strings(tokens)
292 | T := table.NewWriter()
293 | T.AppendHeader(table.Row{"Token Name", "Enabled", "Roles"})
294 | for _, name := range tokens {
295 | token := project.Tokens[name]
296 | T.AppendRow(
297 | table.Row{name, cast.ToString(!token.Disabled), strings.Join(token.Roles, ",")},
298 | )
299 | }
300 | println(T.Render())
301 | case "roles":
302 | err = project.LoadRoles(true)
303 | if err != nil {
304 | return true, g.Error(err, "could not load roles")
305 | }
306 |
307 | columns := iop.Columns{
308 | {Name: "Role", Type: iop.StringType},
309 | {Name: "Connection", Type: iop.StringType},
310 | {Name: "Grant", Type: iop.StringType},
311 | {Name: "Object", Type: iop.StringType},
312 | }
313 | data := iop.NewDataset(columns)
314 | for roleName, role := range project.Roles {
315 | for connName, grant := range role {
316 | for _, object := range grant.AllowRead {
317 | data.Append([]any{roleName, connName, "AllowRead", object})
318 | }
319 |
320 | for _, object := range grant.AllowWrite {
321 | data.Append([]any{roleName, connName, "AllowWrite", object})
322 | }
323 |
324 | if string(grant.AllowSQL) != "" {
325 | data.Append([]any{roleName, connName, "AllowSQL", string(grant.AllowSQL)})
326 | }
327 | }
328 | }
329 |
330 | data.Sort(0, 1, 2)
331 | data.Print(0)
332 | default:
333 | return false, nil
334 | }
335 | return
336 | }
337 |
338 | func cliInit() int {
339 | // init CLI
340 | flaggy.SetName("dbrest")
341 | flaggy.SetDescription("Spin up a REST API for any Major Database | https://github.com/dbrest-io/dbREST")
342 | flaggy.SetVersion(state.Version)
343 | flaggy.DefaultParser.ShowHelpOnUnexpected = true
344 | flaggy.DefaultParser.AdditionalHelpPrepend = "Version " + state.Version
345 |
346 | // make CLI sub-commands
347 | cliConns.Make().Add()
348 | cliServe.Make().Add()
349 | cliTokens.Make().Add()
350 |
351 | for _, cli := range g.CliArr {
352 | flaggy.AttachSubcommand(cli.Sc, 1)
353 | }
354 |
355 | flaggy.ShowHelpOnUnexpectedDisable()
356 | flaggy.Parse()
357 |
358 | ok, err := g.CliProcess()
359 | if err != nil {
360 | g.LogFatal(err)
361 | } else if !ok {
362 | flaggy.ShowHelp("")
363 | }
364 |
365 | return 0
366 | }
367 |
368 | func telemetry(action string) {
369 | // set DBREST_TELEMETRY=FALSE to disable
370 | if val := os.Getenv("DBREST_TELEMETRY"); val != "" {
371 | if !cast.ToBool(val) {
372 | return
373 | }
374 | }
375 |
376 | // deterministic anonymous ID generated per machine
377 | machineID, _ := machineid.ProtectedID("dbrest")
378 |
379 | payload := g.M(
380 | "version", state.Version,
381 | "os", runtime.GOOS,
382 | "action", action,
383 | "machine_id", machineID,
384 | )
385 | net.ClientDo("POST", state.RudderstackURL, strings.NewReader(g.Marshal(payload)), nil)
386 |
387 | }
388 |
389 | func checkVersion() {
390 | if state.Version == "dev" {
391 | return
392 | }
393 |
394 | instruction := "Please download here: https://docs.dbrest.io/installation"
395 | execFileName, _ := osext.Executable()
396 | switch {
397 | case strings.Contains(execFileName, "homebrew"):
398 | instruction = "Please run `brew upgrade dbrest-io/dbrest/dbrest`"
399 | case strings.Contains(execFileName, "scoop"):
400 | instruction = "Please run `scoop update dbrest`"
401 | case execFileName == "/dbrest/dbrest" && os.Getenv("HOME") == "/dbrest":
402 | instruction = "Please run `docker pull dbrest/dbrest` and recreate your container"
403 | }
404 |
405 | const url = "https://api.github.com/repos/dbrest-io/dbREST/tags"
406 | _, respB, _ := net.ClientDo("GET", url, nil, nil)
407 | arr := []map[string]any{}
408 | g.JSONUnmarshal(respB, &arr)
409 | if len(arr) > 0 && arr[0] != nil {
410 | latest := cast.ToString(arr[0]["name"])
411 | isNew, err := g.CompareVersions(state.Version, latest)
412 | if err != nil {
413 | g.DebugLow("Error comparing versions: %s", err.Error())
414 | } else if isNew {
415 | g.Warn("FYI there is a new dbREST version released (%s). %s", latest, instruction)
416 | }
417 | }
418 | }
419 |
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:focal
2 | ENV HOME /dbrest
3 | RUN mkdir /dbrest
4 | WORKDIR /dbrest
5 | COPY dbrest /dbrest/
6 | RUN chmod -R 777 /dbrest && chmod +x /dbrest/dbrest
7 | ENTRYPOINT ["/dbrest/dbrest"]
--------------------------------------------------------------------------------
/env/env.go:
--------------------------------------------------------------------------------
1 | package env
2 |
3 | import (
4 | "os"
5 |
6 | env "github.com/slingdata-io/sling-cli/core/env"
7 | )
8 |
9 | var (
10 | HomeDir = os.Getenv("DBREST_HOME_DIR")
11 | HomeDirEnvFile = ""
12 | Env = &env.EnvFile{}
13 | )
14 |
15 | func init() {
16 |
17 | HomeDir = env.SetHomeDir("dbrest")
18 | HomeDirEnvFile = env.GetEnvFilePath(HomeDir)
19 |
20 | if content := os.Getenv("DBREST_ENV_YAML"); content != "" {
21 | os.Setenv("ENV_YAML", content)
22 | }
23 |
24 | // other sources of creds
25 | env.SetHomeDir("sling") // https://github.com/slingdata-io/sling
26 | env.SetHomeDir("dbnet") // https://github.com/dbnet-io/dbnet
27 |
28 | // create env file if not exists
29 | os.MkdirAll(HomeDir, 0755)
30 | }
31 |
32 | func LoadDbRestEnvFile(envFile string) (ef env.EnvFile) {
33 | ef = env.LoadEnvFile(envFile)
34 | Env = &ef
35 | Env.TopComment = "# Environment Credentials for dbREST\n# See https://docs.dbrest.io/\n"
36 | return
37 | }
38 |
39 | func LoadEnvFile(envFile string) (ef env.EnvFile) {
40 | return env.LoadEnvFile(envFile)
41 | }
42 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/dbrest-io/dbrest
2 |
3 | go 1.23.0
4 |
5 | toolchain go1.23.4
6 |
7 | require (
8 | github.com/denisbrodbeck/machineid v1.0.1
9 | github.com/flarco/g v0.1.145
10 | github.com/integrii/flaggy v1.5.2
11 | github.com/jedib0t/go-pretty v4.3.0+incompatible
12 | github.com/jmoiron/sqlx v1.2.0
13 | github.com/json-iterator/go v1.1.12
14 | github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0
15 | github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61
16 | github.com/samber/lo v1.39.0
17 | github.com/slingdata-io/sling-cli v1.4.8
18 | github.com/spf13/cast v1.7.1
19 | github.com/stretchr/testify v1.10.0
20 | gopkg.in/yaml.v3 v3.0.1
21 | )
22 |
23 | require (
24 | cel.dev/expr v0.19.1 // indirect
25 | cloud.google.com/go v0.118.0 // indirect
26 | cloud.google.com/go/auth v0.13.0 // indirect
27 | cloud.google.com/go/auth/oauth2adapt v0.2.6 // indirect
28 | cloud.google.com/go/bigquery v1.64.0 // indirect
29 | cloud.google.com/go/bigtable v1.33.0 // indirect
30 | cloud.google.com/go/compute/metadata v0.6.0 // indirect
31 | cloud.google.com/go/iam v1.2.2 // indirect
32 | cloud.google.com/go/longrunning v0.6.2 // indirect
33 | cloud.google.com/go/monitoring v1.21.2 // indirect
34 | cloud.google.com/go/storage v1.43.0 // indirect
35 | filippo.io/edwards25519 v1.1.0 // indirect
36 | github.com/360EntSecGroup-Skylar/excelize v1.4.1 // indirect
37 | github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
38 | github.com/99designs/keyring v1.2.2 // indirect
39 | github.com/Azure/azure-sdk-for-go/sdk/azcore v1.13.0 // indirect
40 | github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 // indirect
41 | github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect
42 | github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.4.0 // indirect
43 | github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect
44 | github.com/ClickHouse/ch-go v0.65.1 // indirect
45 | github.com/ClickHouse/clickhouse-go/v2 v2.34.0 // indirect
46 | github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c // indirect
47 | github.com/PuerkitoBio/goquery v1.6.0 // indirect
48 | github.com/andybalholm/brotli v1.1.1 // indirect
49 | github.com/andybalholm/cascadia v1.1.0 // indirect
50 | github.com/apache/arrow/go/v15 v15.0.2 // indirect
51 | github.com/apache/arrow/go/v16 v16.1.0 // indirect
52 | github.com/apache/thrift v0.21.0 // indirect
53 | github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
54 | github.com/aws/aws-sdk-go v1.51.11 // indirect
55 | github.com/aws/aws-sdk-go-v2 v1.30.1 // indirect
56 | github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect
57 | github.com/aws/aws-sdk-go-v2/credentials v1.17.23 // indirect
58 | github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.4 // indirect
59 | github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.13 // indirect
60 | github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.13 // indirect
61 | github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.13 // indirect
62 | github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect
63 | github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.15 // indirect
64 | github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.15 // indirect
65 | github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.13 // indirect
66 | github.com/aws/aws-sdk-go-v2/service/s3 v1.58.0 // indirect
67 | github.com/aws/smithy-go v1.20.3 // indirect
68 | github.com/beorn7/perks v1.0.1 // indirect
69 | github.com/bits-and-blooms/bitset v1.10.0 // indirect
70 | github.com/bits-and-blooms/bloom/v3 v3.7.0 // indirect
71 | github.com/cespare/xxhash/v2 v2.3.0 // indirect
72 | github.com/cncf/xds/go v0.0.0-20241223141626-cff3c89139a3 // indirect
73 | github.com/danieljoos/wincred v1.1.2 // indirect
74 | github.com/davecgh/go-spew v1.1.1 // indirect
75 | github.com/dustin/go-humanize v1.0.1 // indirect
76 | github.com/dvsekhvalnov/jose2go v1.6.0 // indirect
77 | github.com/ebitengine/purego v0.8.0 // indirect
78 | github.com/elastic/elastic-transport-go/v8 v8.6.0 // indirect
79 | github.com/elastic/go-elasticsearch/v8 v8.17.0 // indirect
80 | github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect
81 | github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect
82 | github.com/fatih/color v1.17.0 // indirect
83 | github.com/felixge/httpsnoop v1.0.4 // indirect
84 | github.com/flarco/bigquery v0.0.9 // indirect
85 | github.com/francoispqt/gojay v1.2.13 // indirect
86 | github.com/gabriel-vasile/mimetype v1.4.4 // indirect
87 | github.com/getsentry/sentry-go v0.27.0 // indirect
88 | github.com/go-faster/city v1.0.1 // indirect
89 | github.com/go-faster/errors v0.7.1 // indirect
90 | github.com/go-logr/logr v1.4.2 // indirect
91 | github.com/go-logr/stdr v1.2.2 // indirect
92 | github.com/go-ole/go-ole v1.2.6 // indirect
93 | github.com/go-openapi/errors v0.21.0 // indirect
94 | github.com/go-openapi/strfmt v0.22.0 // indirect
95 | github.com/go-sql-driver/mysql v1.8.1 // indirect
96 | github.com/gobwas/glob v0.2.3 // indirect
97 | github.com/goccy/go-json v0.10.5 // indirect
98 | github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
99 | github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
100 | github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
101 | github.com/golang-sql/sqlexp v0.1.0 // indirect
102 | github.com/golang/snappy v0.0.4 // indirect
103 | github.com/google/flatbuffers v25.2.10+incompatible // indirect
104 | github.com/google/s2a-go v0.1.8 // indirect
105 | github.com/google/uuid v1.6.0 // indirect
106 | github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
107 | github.com/googleapis/gax-go/v2 v2.14.0 // indirect
108 | github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
109 | github.com/hashicorp/errwrap v1.1.0 // indirect
110 | github.com/hashicorp/go-multierror v1.1.1 // indirect
111 | github.com/hashicorp/go-uuid v1.0.3 // indirect
112 | github.com/imdario/mergo v0.3.13 // indirect
113 | github.com/itchyny/timefmt-go v0.1.6 // indirect
114 | github.com/jackc/pgpassfile v1.0.0 // indirect
115 | github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
116 | github.com/jackc/pgx/v5 v5.5.5 // indirect
117 | github.com/jackc/puddle/v2 v2.2.2 // indirect
118 | github.com/jcmturner/aescts/v2 v2.0.0 // indirect
119 | github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
120 | github.com/jcmturner/gofork v1.7.6 // indirect
121 | github.com/jcmturner/goidentity/v6 v6.0.1 // indirect
122 | github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
123 | github.com/jcmturner/rpc/v2 v2.0.3 // indirect
124 | github.com/jinzhu/inflection v1.0.0 // indirect
125 | github.com/jinzhu/now v1.1.5 // indirect
126 | github.com/jlaffaye/ftp v0.2.0 // indirect
127 | github.com/jmespath/go-jmespath v0.4.0 // indirect
128 | github.com/jpillora/backoff v1.0.0 // indirect
129 | github.com/klauspost/asmfmt v1.3.2 // indirect
130 | github.com/klauspost/compress v1.18.0 // indirect
131 | github.com/klauspost/cpuid/v2 v2.2.10 // indirect
132 | github.com/kr/fs v0.1.0 // indirect
133 | github.com/kshedden/datareader v0.0.0-20210325133423-816b6ffdd011 // indirect
134 | github.com/kylelemons/godebug v1.1.0 // indirect
135 | github.com/labstack/echo/v4 v4.10.2 // indirect
136 | github.com/labstack/gommon v0.4.0 // indirect
137 | github.com/lib/pq v1.10.9 // indirect
138 | github.com/linkedin/goavro/v2 v2.12.0 // indirect
139 | github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
140 | github.com/maja42/goval v1.4.0 // indirect
141 | github.com/mattn/go-colorable v0.1.13 // indirect
142 | github.com/mattn/go-isatty v0.0.20 // indirect
143 | github.com/mattn/go-runewidth v0.0.16 // indirect
144 | github.com/mattn/go-sqlite3 v1.14.22 // indirect
145 | github.com/microsoft/go-mssqldb v1.8.0 // indirect
146 | github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 // indirect
147 | github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 // indirect
148 | github.com/mitchellh/mapstructure v1.5.0 // indirect
149 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
150 | github.com/modern-go/reflect2 v1.0.2 // indirect
151 | github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
152 | github.com/montanaflynn/stats v0.7.0 // indirect
153 | github.com/mtibben/percent v0.2.1 // indirect
154 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
155 | github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect
156 | github.com/nqd/flat v0.1.1 // indirect
157 | github.com/oklog/ulid v1.3.1 // indirect
158 | github.com/olekukonko/tablewriter v0.0.5 // indirect
159 | github.com/orcaman/concurrent-map/v2 v2.0.1 // indirect
160 | github.com/parquet-go/parquet-go v0.23.0 // indirect
161 | github.com/paulmach/orb v0.11.1 // indirect
162 | github.com/pierrec/lz4/v4 v4.1.22 // indirect
163 | github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
164 | github.com/pkg/errors v0.9.1 // indirect
165 | github.com/pkg/sftp v1.13.9 // indirect
166 | github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
167 | github.com/pmezard/go-difflib v1.0.0 // indirect
168 | github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
169 | github.com/prometheus/client_golang v1.20.5 // indirect
170 | github.com/prometheus/client_model v0.6.1 // indirect
171 | github.com/prometheus/common v0.55.0 // indirect
172 | github.com/prometheus/procfs v0.15.1 // indirect
173 | github.com/psanford/sqlite3vfs v0.0.0-20220823065410-bd28ac7ee3c2 // indirect
174 | github.com/psanford/sqlite3vfshttp v0.0.0-20220827153928-a19f096e6eb4 // indirect
175 | github.com/rivo/uniseg v0.4.7 // indirect
176 | github.com/rs/zerolog v1.20.0 // indirect
177 | github.com/segmentio/asm v1.2.0 // indirect
178 | github.com/segmentio/encoding v0.4.0 // indirect
179 | github.com/segmentio/ksuid v1.0.4 // indirect
180 | github.com/shirou/gopsutil/v3 v3.24.4 // indirect
181 | github.com/shirou/gopsutil/v4 v4.24.9 // indirect
182 | github.com/shoenig/go-m1cpu v0.1.6 // indirect
183 | github.com/shopspring/decimal v1.4.0 // indirect
184 | github.com/sijms/go-ora/v2 v2.8.24 // indirect
185 | github.com/sirupsen/logrus v1.9.3 // indirect
186 | github.com/slingdata-io/sling v0.0.0-20241011224356-e5fa1b3ebe3b // indirect
187 | github.com/snowflakedb/gosnowflake v1.10.0 // indirect
188 | github.com/timeplus-io/proton-go-driver/v2 v2.0.19 // indirect
189 | github.com/tklauser/go-sysconf v0.3.12 // indirect
190 | github.com/tklauser/numcpus v0.6.1 // indirect
191 | github.com/trinodb/trino-go-client v0.318.0 // indirect
192 | github.com/valyala/bytebufferpool v1.0.0 // indirect
193 | github.com/valyala/fasttemplate v1.2.2 // indirect
194 | github.com/viant/xunsafe v0.8.0 // indirect
195 | github.com/xdg-go/pbkdf2 v1.0.0 // indirect
196 | github.com/xdg-go/scram v1.1.2 // indirect
197 | github.com/xdg-go/stringprep v1.0.4 // indirect
198 | github.com/xo/dburl v0.3.0 // indirect
199 | github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect
200 | github.com/yusufpapurcu/wmi v1.2.4 // indirect
201 | github.com/zeebo/xxh3 v1.0.2 // indirect
202 | go.mongodb.org/mongo-driver v1.14.0 // indirect
203 | go.opentelemetry.io/auto/sdk v1.1.0 // indirect
204 | go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.54.0 // indirect
205 | go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 // indirect
206 | go.opentelemetry.io/otel v1.35.0 // indirect
207 | go.opentelemetry.io/otel/metric v1.35.0 // indirect
208 | go.opentelemetry.io/otel/sdk v1.34.0 // indirect
209 | go.opentelemetry.io/otel/sdk/metric v1.34.0 // indirect
210 | go.opentelemetry.io/otel/trace v1.35.0 // indirect
211 | golang.org/x/crypto v0.33.0 // indirect
212 | golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect
213 | golang.org/x/mod v0.23.0 // indirect
214 | golang.org/x/net v0.35.0 // indirect
215 | golang.org/x/oauth2 v0.25.0 // indirect
216 | golang.org/x/sync v0.11.0 // indirect
217 | golang.org/x/sys v0.31.0 // indirect
218 | golang.org/x/term v0.29.0 // indirect
219 | golang.org/x/text v0.22.0 // indirect
220 | golang.org/x/time v0.8.0 // indirect
221 | golang.org/x/tools v0.30.0 // indirect
222 | golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
223 | google.golang.org/api v0.214.0 // indirect
224 | google.golang.org/genproto v0.0.0-20241118233622-e639e219e697 // indirect
225 | google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 // indirect
226 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect
227 | google.golang.org/grpc v1.71.0 // indirect
228 | google.golang.org/protobuf v1.36.5 // indirect
229 | gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
230 | gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
231 | gopkg.in/yaml.v2 v2.4.0 // indirect
232 | gorm.io/driver/postgres v1.5.7 // indirect
233 | gorm.io/driver/sqlite v1.5.5 // indirect
234 | gorm.io/gorm v1.25.11 // indirect
235 | )
236 |
237 | replace github.com/slingdata-io/sling-cli => ../sling-cli
238 |
239 | replace github.com/flarco/g => ../g
240 |
--------------------------------------------------------------------------------
/scripts/prep.gomod.sh:
--------------------------------------------------------------------------------
1 | set -e # exit on error
2 |
3 | echo 'prep.gomod.sh'
4 | go mod edit -dropreplace='github.com/flarco/g' go.mod
5 | go mod edit -dropreplace='github.com/slingdata-io/sling-cli' go.mod
6 | go mod edit -droprequire='github.com/slingdata-io/sling' go.mod
7 | # go get github.com/flarco/g@HEAD
8 | # go get github.com/slingdata-io/sling-cli@HEAD
9 | go mod tidy
--------------------------------------------------------------------------------
/server/request.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "io"
5 | "net/http"
6 | "net/url"
7 | "strings"
8 |
9 | "github.com/dbrest-io/dbrest/state"
10 | "github.com/flarco/g"
11 | "github.com/labstack/echo/v5"
12 | "github.com/samber/lo"
13 | "github.com/slingdata-io/sling-cli/core/dbio"
14 | "github.com/slingdata-io/sling-cli/core/dbio/connection"
15 | "github.com/slingdata-io/sling-cli/core/dbio/database"
16 | "github.com/slingdata-io/sling-cli/core/dbio/filesys"
17 | "github.com/slingdata-io/sling-cli/core/dbio/iop"
18 | "github.com/spf13/cast"
19 | )
20 |
21 | // Request is the typical request struct
22 | type Request struct {
23 | ID string `json:"id" query:"id"` // used for query ID
24 | Name string `json:"name" query:"name"`
25 | Connection string `json:"connection" query:"connection"`
26 | Database string `json:"database" query:"database"`
27 | Schema string `json:"schema" query:"schema"`
28 | Table string `json:"table" query:"table"`
29 | Query string `json:"query" query:"query"`
30 | Procedure string `json:"procedure" query:"procedure"`
31 | Data any `json:"data" query:"data"`
32 |
33 | Project *state.Project `json:"-" query:"-"`
34 | conn connection.Connection `json:"-" query:"-"`
35 | Header http.Header `json:"-" query:"-"`
36 | dbTable database.Table `json:"-" query:"-"`
37 | Roles state.RoleMap `json:"-" query:"-"`
38 | Permissions state.Permissions `json:"-" query:"-"`
39 | echoCtx echo.Context `json:"-" query:"-"`
40 | }
41 |
42 | func NewRequest(c echo.Context) Request {
43 |
44 | req := Request{
45 | ID: c.PathParam("id"),
46 | Connection: strings.ToLower(c.PathParam("connection")),
47 | Schema: c.PathParam("schema"),
48 | Table: c.PathParam("table"),
49 | Database: c.QueryParam("database"),
50 | echoCtx: c,
51 | Header: c.Request().Header,
52 | Roles: state.RoleMap{},
53 | Permissions: state.Permissions{},
54 | }
55 |
56 | // set for middleware
57 | defer func() { c.Set("request", &req) }()
58 |
59 | req.ID = lo.Ternary(req.ID == "", c.QueryParam("id"), req.ID)
60 | req.Schema = lo.Ternary(req.Schema == "", c.QueryParam("schema"), req.Schema)
61 |
62 | // set project
63 | projectName := req.Header.Get("X-Project-ID")
64 | projectName = lo.Ternary(projectName == "", state.DefaultProjectID, projectName)
65 | req.Project = state.LoadProject(projectName)
66 | if req.Project == nil {
67 | return req
68 | }
69 |
70 | // parse table name
71 | conn, err := req.Project.GetConnObject(req.Connection, "")
72 | if err == nil && req.Schema != "" {
73 | if req.Table != "" {
74 | fullName := req.Schema + "." + req.Table
75 | req.dbTable, _ = database.ParseTableName(fullName, conn.Type)
76 | req.Schema = req.dbTable.Schema
77 | req.Table = req.dbTable.Name
78 | } else {
79 | fullName := req.Schema + ".*"
80 | t, _ := database.ParseTableName(fullName, conn.Type)
81 | req.Schema = t.Schema
82 | }
83 | }
84 | req.conn = conn
85 |
86 | // set permissions
87 | if req.Project.NoRestriction {
88 | req.Roles = state.AllowAllRoleMap
89 | req.Permissions = state.Permissions{
90 | "*": state.PermissionReadWrite, // read/write access
91 | }
92 | } else if authToken := c.Request().Header.Get("Authorization"); authToken != "" {
93 | // token -> roles -> grants
94 | req.Project.LoadTokens(false) // load tokens, do not force, cached & throttled
95 | token, ok := req.Project.ResolveToken(authToken)
96 | if ok && !token.Disabled {
97 | req.Project.LoadRoles(false) // load roles, do not force, cached & throttled
98 | req.Roles = req.Project.GetRoleMap(token.Roles)
99 | req.Permissions = req.Roles.GetPermissions(conn)
100 | }
101 | }
102 |
103 | return req
104 | }
105 |
106 | func (r *Request) CanRead(table database.Table) bool {
107 | if p, ok := r.Permissions["*"]; ok {
108 | if p.CanRead() {
109 | return true
110 | }
111 | }
112 | ts := r.Project.SchemaAll(r.Connection, table.Schema)
113 | if p, ok := r.Permissions[ts.FullName()]; ok {
114 | if p.CanRead() {
115 | return true
116 | }
117 | }
118 |
119 | if p, ok := r.Permissions[table.FullName()]; ok {
120 | if p.CanRead() {
121 | return true
122 | }
123 | }
124 |
125 | return false
126 | }
127 |
128 | func (r *Request) URL() *url.URL {
129 | return r.echoCtx.Request().URL
130 | }
131 |
132 | func (r *Request) CanWrite(table database.Table) bool {
133 | if p, ok := r.Permissions["*"]; ok {
134 | if p.CanWrite() {
135 | return true
136 | }
137 | }
138 |
139 | ts := r.Project.SchemaAll(r.Connection, table.Schema)
140 | if p, ok := r.Permissions[ts.FullName()]; ok {
141 | if p.CanWrite() {
142 | return true
143 | }
144 | }
145 |
146 | if p, ok := r.Permissions[table.FullName()]; ok {
147 | if p.CanWrite() {
148 | return true
149 | }
150 | }
151 |
152 | return false
153 | }
154 |
155 | func (req *Request) GetDatastream() (ds *iop.Datastream, err error) {
156 | ctx := req.echoCtx.Request().Context()
157 |
158 | // whether to flatten json, default is true
159 | flatten := req.echoCtx.QueryParam("flatten")
160 |
161 | cfg := map[string]string{
162 | "flatten": lo.Ternary(flatten == "", "true", flatten),
163 | "delimiter": req.echoCtx.QueryParam("delimiter"),
164 | "header": req.echoCtx.QueryParam("header"),
165 | "datetime_format": req.echoCtx.QueryParam("datetime_format"),
166 | }
167 | ds = iop.NewDatastreamContext(ctx, nil)
168 | ds.SafeInference = true
169 | ds.SetConfig(cfg)
170 |
171 | contentType := strings.ToLower(req.Header.Get("Content-Type"))
172 | reader := req.echoCtx.Request().Body
173 |
174 | switch contentType {
175 | case "multipart/form-data":
176 | reader, err = req.GetFileUpload()
177 | if err != nil {
178 | err = g.Error(err, "could not get file reader")
179 | return
180 | }
181 |
182 | ft, reader, err := filesys.PeekFileType(reader)
183 | if err != nil {
184 | err = g.Error(err, "could not peek file reader")
185 | return ds, err
186 | }
187 |
188 | switch ft {
189 | case dbio.FileTypeCsv:
190 | err = ds.ConsumeCsvReader(reader)
191 | case dbio.FileTypeXml:
192 | err = ds.ConsumeXmlReader(reader)
193 | case dbio.FileTypeJson:
194 | err = ds.ConsumeJsonReader(reader)
195 | }
196 | if err != nil {
197 | err = g.Error(err, "could not consume reader")
198 | return ds, err
199 | }
200 | case "text/plain", "text/csv":
201 | err = ds.ConsumeCsvReader(reader)
202 | case "application/xml":
203 | err = ds.ConsumeXmlReader(reader)
204 | default:
205 | err = ds.ConsumeJsonReader(reader)
206 | }
207 | if err != nil {
208 | err = g.Error(err, "could not consume reader")
209 | return
210 | }
211 |
212 | err = ds.WaitReady()
213 | if err != nil {
214 | err = g.Error(err, "error waiting for datastream")
215 | return
216 | }
217 |
218 | return
219 | }
220 |
221 | func (r *Request) GetFileUpload() (src io.ReadCloser, err error) {
222 | file, err := r.echoCtx.FormFile("file")
223 | if err != nil {
224 | err = g.Error(err, "could not open form file")
225 | return
226 | }
227 |
228 | src, err = file.Open()
229 | if err != nil {
230 | err = g.Error(err, "could not open file")
231 | return
232 | }
233 |
234 | return
235 | }
236 |
237 | type requestCheck string
238 |
239 | const (
240 | reqCheckID requestCheck = "id"
241 | reqCheckName requestCheck = "name"
242 | reqCheckConnection requestCheck = "connection"
243 | reqCheckDatabase requestCheck = "database"
244 | reqCheckSchema requestCheck = "schema"
245 | reqCheckTable requestCheck = "table"
246 | reqCheckQuery requestCheck = "query"
247 | reqCheckProcedure requestCheck = "procedure"
248 | reqCheckData requestCheck = "data"
249 | )
250 |
251 | func (r *Request) Validate(checks ...requestCheck) (err error) {
252 | eG := g.ErrorGroup{}
253 |
254 | // always check project
255 | if r.Project == nil {
256 | eG.Add(g.Error("missing request value for: project"))
257 | }
258 |
259 | for _, check := range checks {
260 | switch check {
261 | case reqCheckName:
262 | if cast.ToString(r.Name) == "" {
263 | eG.Add(g.Error("missing request value for: name"))
264 | }
265 | case reqCheckConnection:
266 | if cast.ToString(r.Connection) == "" {
267 | eG.Add(g.Error("missing request value for: connection"))
268 | } else if !r.Roles.HasAccess(r.Connection) {
269 | eG.Add(g.Error("forbidden access for: connection"))
270 | }
271 | case reqCheckDatabase:
272 | if cast.ToString(r.Database) == "" {
273 | eG.Add(g.Error("missing request value for: database"))
274 | }
275 | case reqCheckSchema:
276 | if cast.ToString(r.Schema) == "" {
277 | eG.Add(g.Error("missing request value for: schema"))
278 | }
279 | case reqCheckTable:
280 | if cast.ToString(r.Table) == "" {
281 | eG.Add(g.Error("missing request value for: table"))
282 | } else if !(r.CanRead(r.dbTable) || r.CanWrite(r.dbTable)) {
283 | eG.Add(g.Error("forbidden access for: table"))
284 | }
285 | case reqCheckID:
286 | if r.ID == "" {
287 | eG.Add(g.Error("missing request value for: id"))
288 | }
289 | case reqCheckQuery:
290 | if cast.ToString(r.Query) == "" {
291 | eG.Add(g.Error("missing request value for: query"))
292 | }
293 | case reqCheckProcedure:
294 | if cast.ToString(r.Procedure) == "" {
295 | eG.Add(g.Error("missing request value for: procedure"))
296 | }
297 | case reqCheckData:
298 | if cast.ToString(r.Data) == "" {
299 | eG.Add(g.Error("missing request value for: data"))
300 | }
301 | }
302 | }
303 |
304 | // token has role
305 | if len(r.Roles) == 0 {
306 | eG.Add(g.Error("Invalid token or forbidden"))
307 | }
308 |
309 | return eG.Err()
310 | }
311 |
312 | // ReqFunction is the request function type
313 | type ReqFunction func(c database.Connection, req Request) (iop.Dataset, error)
314 |
315 | // ProcessRequest processes the request with the given function
316 | func ProcessRequest(req Request, reqFunc ReqFunction) (data iop.Dataset, err error) {
317 | c, err := req.Project.GetConnInstance(req.Connection, req.Database)
318 | if err != nil {
319 | err = g.Error(err, "could not get conn %s", req.Connection)
320 | return
321 | }
322 |
323 | return reqFunc(c, req)
324 | }
325 |
--------------------------------------------------------------------------------
/server/response.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "io"
5 | "net/http"
6 | "strings"
7 | "time"
8 |
9 | "github.com/flarco/g"
10 | "github.com/flarco/g/csv"
11 | "github.com/labstack/echo/v5"
12 | "github.com/samber/lo"
13 | "github.com/slingdata-io/sling-cli/core/dbio/iop"
14 | "github.com/spf13/cast"
15 | )
16 |
17 | type Response struct {
18 | Request Request `json:"-"`
19 | Error string `json:"error,omitempty"`
20 | Payload map[string]any `json:"-"`
21 | Status int `json:"-"`
22 | ds *iop.Datastream `json:"-"`
23 | data iop.Dataset `json:"-"`
24 | ec echo.Context `json:"-" query:"-"`
25 | Header http.Header `json:"-" query:"-"`
26 | }
27 |
28 | func NewResponse(req Request) Response {
29 | resp := Response{
30 | Request: req,
31 | ec: req.echoCtx,
32 | Status: 200,
33 | Header: req.echoCtx.Response().Header(),
34 | }
35 | resp.Header.Set("X-Request-ID", req.ID)
36 | resp.Header.Set("Access-Control-Expose-Headers", "X-Request-ID, X-Request-Columns, X-Request-Status, X-Request-Continue, X-Project-ID")
37 | return resp
38 | }
39 |
40 | func (r *Response) MakeStreaming() (err error) {
41 |
42 | if r.ds == nil {
43 | return r.ec.String(http.StatusOK, "")
44 | }
45 |
46 | r.setHeaderColumns(r.ds.Columns)
47 | ////////////////////
48 |
49 | respW := r.ec.Response().Writer
50 | var pushRow func(row []interface{})
51 |
52 | fields := r.ds.Columns.Names()
53 | acceptType := strings.ToLower(r.ec.Request().Header.Get(echo.HeaderAccept))
54 |
55 | switch acceptType {
56 | case "text/plain":
57 | r.Header.Set("Content-Type", "text/plain")
58 | csvW := csv.NewWriter(respW)
59 | csvW.Comma = '\t' // TSV
60 |
61 | // write headers
62 | csvW.Write(fields)
63 | csvW.Flush()
64 |
65 | pushRow = func(row []interface{}) {
66 | _, err = csvW.Write(r.ds.CastRowToString(row))
67 | if err != nil {
68 | r.ds.Context.Cancel()
69 | g.LogError(g.Error(err, "could not encode csv row"))
70 | }
71 | csvW.Flush()
72 | }
73 | case "text/csv":
74 | r.Header.Set("Content-Type", "text/csv")
75 | csvW := csv.NewWriter(respW)
76 |
77 | // write headers
78 | csvW.Write(fields)
79 | csvW.Flush()
80 |
81 | pushRow = func(row []interface{}) {
82 | _, err = csvW.Write(r.ds.CastRowToString(row))
83 | if err != nil {
84 | r.ds.Context.Cancel()
85 | g.LogError(g.Error(err, "could not encode csv row"))
86 | }
87 | csvW.Flush()
88 | }
89 |
90 | case "application/json":
91 | r.Header.Set("Content-Type", "application/json")
92 | data, err := r.ds.Collect(0)
93 | if err != nil {
94 | r.ds.Context.Cancel()
95 | g.LogError(g.Error(err, "could not encode json payload"))
96 | }
97 | // convert all values to string since JS can truncate int values
98 | // above Number.MAX_SAFE_INTEGER
99 | out, _ := g.JSONMarshal(StringRecords(&data))
100 | respW.Write(out)
101 | default:
102 | r.Header.Set("Content-Type", "application/jsonlines")
103 |
104 | enc := json.NewEncoder(respW)
105 | pushRow = func(row []interface{}) {
106 | err := enc.Encode(row)
107 | if err != nil {
108 | r.ds.Context.Cancel()
109 | g.LogError(g.Error(err, "could not encode json record"))
110 | }
111 | }
112 | columnsI := lo.Map(r.ds.Columns, func(c iop.Column, i int) any {
113 | return c.Name
114 | })
115 | pushRow(columnsI) // first row is columns
116 | }
117 |
118 | // write headers
119 | r.Header.Set("Transfer-Encoding", "chunked")
120 | r.ec.Response().WriteHeader(r.Status)
121 | r.ec.Response().Flush()
122 |
123 | ctx := r.ec.Request().Context()
124 | for row := range r.ds.Rows() {
125 |
126 | select {
127 | case <-ctx.Done():
128 | r.ds.Context.Cancel()
129 | if err = r.ds.Err(); err != nil {
130 | return ErrJSON(http.StatusInternalServerError, err)
131 | }
132 | return
133 | default:
134 | pushRow(row)
135 | r.ec.Response().Flush()
136 | }
137 | }
138 |
139 | return
140 | }
141 |
142 | func (r *Response) Make() (err error) {
143 |
144 | if r.Payload != nil {
145 | r.Header.Set("Content-Type", "application/json")
146 | return r.ec.JSON(r.Status, r.Payload)
147 | }
148 |
149 | out := ""
150 | acceptType := r.ec.Request().Header.Get(echo.HeaderAccept)
151 | switch strings.ToLower(acceptType) {
152 | case "text/plain", "text/csv":
153 | r.Header.Set("Content-Type", "text/csv")
154 | if r.ds != nil {
155 | reader := r.ds.NewCsvReader(iop.DefaultStreamConfig())
156 | b, _ := io.ReadAll(reader)
157 | out = string(b)
158 | } else if len(r.data.Columns) > 0 {
159 | r.setHeaderColumns(r.data.Columns)
160 | reader := r.data.Stream().NewCsvReader(iop.DefaultStreamConfig())
161 | b, _ := io.ReadAll(reader)
162 | out = string(b)
163 | }
164 | case "application/json":
165 | r.Header.Set("Content-Type", "application/json")
166 | if r.ds != nil {
167 | data, _ := r.ds.Collect(0)
168 | r.data = data
169 | }
170 |
171 | if len(r.data.Columns) > 0 {
172 | r.setHeaderColumns(r.data.Columns)
173 | out = g.Marshal(r.data.Records(false))
174 | }
175 | default:
176 | r.Header.Set("Content-Type", "application/jsonlines")
177 | if r.ds != nil {
178 | data, _ := r.ds.Collect(0)
179 | r.data = data
180 | }
181 |
182 | if len(r.data.Columns) > 0 {
183 | r.setHeaderColumns(r.data.Columns)
184 | lines := []string{g.Marshal(r.data.Columns.Names())}
185 | for _, row := range r.data.Rows {
186 | lines = append(lines, g.Marshal(row))
187 | }
188 | out = strings.Join(lines, "\n")
189 | }
190 | }
191 | return r.ec.String(r.Status, out)
192 | }
193 |
194 | func (r Response) setHeaderColumns(cols iop.Columns) {
195 | columnsS := lo.Map(cols, func(c iop.Column, i int) any {
196 | return []string{c.Name, string(c.Type), c.DbType}
197 | })
198 | r.Header.Set("X-Request-Columns", g.Marshal(columnsS))
199 | }
200 |
201 | // Records return rows of maps or string values
202 | func StringRecords(data *iop.Dataset) []map[string]interface{} {
203 | records := make([]map[string]interface{}, len(data.Rows))
204 | for i, row := range data.Rows {
205 | rec := map[string]interface{}{}
206 | for j, field := range data.GetFields(false) {
207 | switch v := row[j].(type) {
208 | case nil:
209 | rec[field] = nil
210 | case time.Time:
211 | rec[field] = strings.ReplaceAll(v.Format("2006-01-02 15:04:05.000000Z07"), " 00:00:00.000000Z", "")
212 | case *time.Time:
213 | rec[field] = strings.ReplaceAll(v.Format("2006-01-02 15:04:05.000000Z07"), " 00:00:00.000000Z", "")
214 | default:
215 | rec[field] = cast.ToString(v)
216 | }
217 | }
218 | records[i] = rec
219 | }
220 | return records
221 | }
222 |
--------------------------------------------------------------------------------
/server/routes.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/dbrest-io/dbrest/state"
7 | "github.com/flarco/g"
8 | jsoniter "github.com/json-iterator/go"
9 | "github.com/labstack/echo/v5"
10 | )
11 |
12 | var json = jsoniter.ConfigCompatibleWithStandardLibrary
13 |
14 | var StandardRoutes = []echo.Route{
15 | {
16 | Name: "getStatus",
17 | Method: "GET",
18 | Path: "/.status",
19 | Handler: getStatus,
20 | },
21 | {
22 | Name: "getConnections",
23 | Method: "GET",
24 | Path: "/.connections",
25 | Handler: getConnections,
26 | },
27 | {
28 | Name: "closeConnection",
29 | Method: "POST",
30 | Path: "/:connection/.close",
31 | Handler: closeConnection,
32 | },
33 | {
34 | Name: "getConnectionDatabases",
35 | Method: "GET",
36 | Path: "/:connection/.databases",
37 | Handler: getConnectionDatabases,
38 | },
39 | {
40 | Name: "getConnectionSchemas",
41 | Method: "GET",
42 | Path: "/:connection/.schemas",
43 | Handler: getConnectionSchemas,
44 | },
45 | {
46 | Name: "getConnectionTables",
47 | Method: "GET",
48 | Path: "/:connection/.tables",
49 | Handler: getConnectionTables,
50 | },
51 | {
52 | Name: "getConnectionColumns",
53 | Method: "GET",
54 | Path: "/:connection/.columns",
55 | Handler: getConnectionColumns,
56 | },
57 | {
58 | Name: "submitSQL",
59 | Method: "POST",
60 | Path: "/:connection/.sql",
61 | Handler: postConnectionSQL,
62 | },
63 | {
64 | Name: "submitSQL_ID",
65 | Method: "POST",
66 | Path: "/:connection/.sql/:id",
67 | Handler: postConnectionSQL,
68 | },
69 | {
70 | Name: "cancelSQL",
71 | Method: "POST",
72 | Path: "/:connection/.cancel/:id",
73 | Handler: postConnectionCancel,
74 | },
75 | {
76 | Name: "getSchemaTables",
77 | Method: "GET",
78 | Path: "/:connection/:schema/.tables",
79 | Handler: getSchemaTables,
80 | },
81 | {
82 | Name: "getSchemaColumns",
83 | Method: "GET",
84 | Path: "/:connection/:schema/.columns",
85 | Handler: getSchemaColumns,
86 | },
87 | {
88 | Name: "getTableColumns",
89 | Method: "GET",
90 | Path: "/:connection/:schema/:table/.columns",
91 | Handler: getTableColumns,
92 | },
93 | {
94 | Name: "getTableIndexes",
95 | Method: "GET",
96 | Path: "/:connection/:schema/:table/.indexes",
97 | Handler: getTableIndexes,
98 | },
99 | {
100 | Name: "getTableKeys",
101 | Method: "GET",
102 | Path: "/:connection/:schema/:table/.keys",
103 | Handler: getTableKeys,
104 | },
105 | {
106 | Name: "tableInsert",
107 | Method: "POST",
108 | Path: "/:connection/:schema/:table",
109 | Handler: postTableInsert,
110 | },
111 | {
112 | Name: "tableUpsert",
113 | Method: "PUT",
114 | Path: "/:connection/:schema/:table",
115 | Handler: postTableUpsert,
116 | },
117 | {
118 | Name: "tableUpdate",
119 | Method: "PATCH",
120 | Path: "/:connection/:schema/:table",
121 | Handler: patchTableUpdate,
122 | },
123 | {
124 | Name: "getTableSelect",
125 | Method: "GET",
126 | Path: "/:connection/:schema/:table",
127 | Handler: getTableSelect,
128 | },
129 | }
130 |
131 | func getStatus(c echo.Context) (err error) {
132 | out := g.F("dbREST %s", state.Version)
133 | return c.String(http.StatusOK, out)
134 | }
135 |
--------------------------------------------------------------------------------
/server/routes_connection.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "net/http"
5 | "strings"
6 |
7 | "github.com/flarco/g"
8 | "github.com/labstack/echo/v5"
9 | "github.com/samber/lo"
10 | "github.com/slingdata-io/sling-cli/core/dbio/database"
11 | "github.com/slingdata-io/sling-cli/core/dbio/iop"
12 | "github.com/spf13/cast"
13 | )
14 |
15 | func getConnections(c echo.Context) (err error) {
16 | req := NewRequest(c)
17 | resp := NewResponse(req)
18 |
19 | if err = req.Validate(); err != nil {
20 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
21 | }
22 |
23 | // load fresh connections
24 | req.Project.LoadConnections(true)
25 |
26 | columns := iop.Columns{
27 | {Name: "name", Type: iop.StringType},
28 | {Name: "type", Type: iop.StringType},
29 | {Name: "database", Type: iop.StringType},
30 | {Name: "source", Type: iop.StringType},
31 | }
32 | resp.data = iop.NewDataset(columns)
33 | for _, conn := range req.Project.Connections {
34 | connName := strings.ToLower(conn.Conn.Info().Name)
35 | if !req.Roles.HasAccess(connName) {
36 | continue
37 | }
38 |
39 | row := []any{
40 | connName,
41 | conn.Conn.Info().Type,
42 | conn.Conn.Info().Database,
43 | conn.Source,
44 | }
45 | resp.data.Append(row)
46 | }
47 |
48 | resp.data.Sort(0, true)
49 |
50 | return resp.Make()
51 | }
52 |
53 | func closeConnection(c echo.Context) (err error) {
54 | req := NewRequest(c)
55 | resp := NewResponse(req)
56 |
57 | if err = req.Validate(reqCheckConnection); err != nil {
58 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
59 | }
60 |
61 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
62 | err = c.Close()
63 | return
64 | }
65 |
66 | resp.data, err = ProcessRequest(req, rf)
67 | if err != nil {
68 | return ErrJSON(http.StatusInternalServerError, err, "could not close connection")
69 | }
70 |
71 | // for middleware
72 | req.echoCtx.Set("data", &resp.data)
73 |
74 | return resp.Make()
75 | }
76 |
77 | func getConnectionDatabases(c echo.Context) (err error) {
78 | req := NewRequest(c)
79 | resp := NewResponse(req)
80 |
81 | if err = req.Validate(reqCheckConnection); err != nil {
82 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
83 | }
84 |
85 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
86 | return c.GetDatabases()
87 | }
88 |
89 | resp.data, err = ProcessRequest(req, rf)
90 | if err != nil {
91 | return ErrJSON(http.StatusInternalServerError, err, "could not get databases")
92 | }
93 |
94 | resp.data.Sort(0, true)
95 |
96 | // for middleware
97 | req.echoCtx.Set("data", &resp.data)
98 |
99 | return resp.Make()
100 | }
101 |
102 | func getConnectionSchemas(c echo.Context) (err error) {
103 | req := NewRequest(c)
104 | resp := NewResponse(req)
105 |
106 | if err = req.Validate(reqCheckConnection); err != nil {
107 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
108 | }
109 |
110 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
111 | data, err = c.GetSchemas()
112 | data.Rows = lo.Filter(data.Rows, func(row []any, i int) bool {
113 | schema := strings.ToLower(cast.ToString(row[0]))
114 | ts := req.Project.SchemaAll(req.Connection, schema)
115 | return req.CanRead(ts) || req.CanWrite(ts)
116 | })
117 |
118 | return
119 | }
120 |
121 | resp.data, err = ProcessRequest(req, rf)
122 | if err != nil {
123 | return ErrJSON(http.StatusInternalServerError, err, "could not get schemas")
124 | }
125 |
126 | resp.data.Sort(0, true)
127 |
128 | // for middleware
129 | req.echoCtx.Set("data", &resp.data)
130 |
131 | return resp.Make()
132 | }
133 |
134 | func getConnectionTables(c echo.Context) (err error) {
135 | req := NewRequest(c)
136 |
137 | if err = req.Validate(reqCheckConnection); err != nil {
138 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
139 | }
140 |
141 | resp, err := getSchemataTables(req)
142 | if err != nil {
143 | return ErrJSON(http.StatusInternalServerError, err, "could not get tables")
144 | }
145 |
146 | return resp.Make()
147 | }
148 |
149 | func getConnectionColumns(c echo.Context) (err error) {
150 | req := NewRequest(c)
151 |
152 | if err = req.Validate(reqCheckConnection); err != nil {
153 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
154 | }
155 |
156 | resp, err := getSchemataColumns(req)
157 | if err != nil {
158 | return ErrJSON(http.StatusInternalServerError, err, "could not get columns")
159 | }
160 |
161 | return resp.Make()
162 | }
163 |
164 | func getSchemaTables(c echo.Context) (err error) {
165 | req := NewRequest(c)
166 |
167 | if err = req.Validate(reqCheckConnection, reqCheckSchema); err != nil {
168 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
169 | }
170 |
171 | resp, err := getSchemataTables(req)
172 | if err != nil {
173 | return ErrJSON(http.StatusInternalServerError, err, "could not get tables")
174 | }
175 |
176 | return resp.Make()
177 | }
178 |
179 | func getSchemaColumns(c echo.Context) (err error) {
180 | req := NewRequest(c)
181 |
182 | if err = req.Validate(reqCheckConnection, reqCheckSchema); err != nil {
183 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
184 | }
185 |
186 | resp, err := getSchemataColumns(req)
187 | if err != nil {
188 | return ErrJSON(http.StatusInternalServerError, err, "could not get columns")
189 | }
190 |
191 | return resp.Make()
192 | }
193 |
194 | func getSchemataTables(req Request) (resp Response, err error) {
195 | resp = NewResponse(req)
196 |
197 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
198 | schemata, err := c.GetSchemata(database.SchemataLevelTable, req.Schema)
199 | if err != nil {
200 | err = g.Error(err, "could not get tables")
201 | return
202 | }
203 |
204 | columns := iop.Columns{
205 | {Name: "database_name", Type: iop.StringType},
206 | {Name: "schema_name", Type: iop.StringType},
207 | {Name: "table_name", Type: iop.StringType},
208 | {Name: "table_type", Type: iop.StringType},
209 | }
210 | data = iop.NewDataset(columns)
211 | for _, table := range schemata.Tables() {
212 | if !(req.CanRead(table) || req.CanWrite(table)) {
213 | continue
214 | }
215 | row := []any{
216 | table.Database,
217 | table.Schema,
218 | table.Name,
219 | lo.Ternary(table.IsView, "view", "table"),
220 | }
221 | data.Append(row)
222 | }
223 |
224 | data.Sort(0, 1, 2)
225 |
226 | // for middleware
227 | req.echoCtx.Set("data", &data)
228 |
229 | return
230 | }
231 |
232 | resp.data, err = ProcessRequest(req, rf)
233 | if err != nil {
234 | err = g.Error(err, "could not get schemas")
235 | return
236 | }
237 |
238 | return resp, nil
239 | }
240 |
241 | func getSchemataColumns(req Request) (resp Response, err error) {
242 |
243 | resp = NewResponse(req)
244 |
245 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
246 | schemata, err := c.GetSchemata(database.SchemataLevelColumn, req.Schema, req.Table)
247 | if err != nil {
248 | err = g.Error(err, "could not get columns")
249 | return
250 | }
251 |
252 | columns := iop.Columns{
253 | {Name: "database_name", Type: iop.StringType},
254 | {Name: "schema_name", Type: iop.StringType},
255 | {Name: "table_name", Type: iop.StringType},
256 | {Name: "table_type", Type: iop.StringType},
257 | {Name: "column_id", Type: iop.IntegerType},
258 | {Name: "column_name", Type: iop.BoolType},
259 | {Name: "column_type", Type: iop.BoolType},
260 | }
261 | data = iop.NewDataset(columns)
262 | for _, table := range schemata.Tables() {
263 | if !(req.CanRead(table) || req.CanWrite(table)) {
264 | continue
265 | }
266 |
267 | for _, column := range table.Columns {
268 | row := []any{
269 | table.Database,
270 | table.Schema,
271 | table.Name,
272 | lo.Ternary(table.IsView, "view", "table"),
273 | column.Position,
274 | column.Name,
275 | column.DbType,
276 | }
277 | data.Append(row)
278 | }
279 | }
280 |
281 | data.Sort(0, 1, 2, 4)
282 |
283 | // for middleware
284 | req.echoCtx.Set("data", &data)
285 |
286 | return
287 | }
288 |
289 | resp.data, err = ProcessRequest(req, rf)
290 | if err != nil {
291 | err = g.Error(err, "could not get columns")
292 | return
293 | }
294 |
295 | return resp, nil
296 | }
297 |
--------------------------------------------------------------------------------
/server/routes_query.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "context"
5 | "io"
6 | "net/http"
7 | "time"
8 |
9 | "github.com/dbrest-io/dbrest/state"
10 | "github.com/flarco/g"
11 | "github.com/labstack/echo/v5"
12 | "github.com/samber/lo"
13 | "github.com/spf13/cast"
14 | )
15 |
16 | func postConnectionSQL(c echo.Context) (err error) {
17 |
18 | req := NewRequest(c)
19 |
20 | // read query text
21 | body, _ := io.ReadAll(c.Request().Body)
22 | req.Query = string(body)
23 |
24 | if !req.Roles.CanSQL(req.Connection) {
25 | return g.ErrJSON(http.StatusForbidden, g.Error("Not allowed to submit custom SQL"))
26 | }
27 |
28 | return processQueryRequest(req)
29 | }
30 |
31 | func postConnectionCancel(c echo.Context) (err error) {
32 |
33 | req := NewRequest(c)
34 | resp := NewResponse(req)
35 |
36 | if err = req.Validate(reqCheckConnection, reqCheckID); err != nil {
37 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
38 | } else if !req.Roles.CanSQL(req.Connection) {
39 | return g.ErrJSON(http.StatusForbidden, g.Error("Not allowed to cancel"))
40 | }
41 |
42 | query := req.Project.NewQuery(context.Background())
43 | query.Conn = req.Connection
44 | query.ID = req.ID
45 | req.echoCtx.Set("query", query)
46 |
47 | err = query.Cancel()
48 | if err != nil {
49 | return ErrJSON(http.StatusInternalServerError, err, "could not cancel query")
50 | }
51 |
52 | return resp.Make()
53 | }
54 |
55 | func processQueryRequest(req Request) (err error) {
56 | // default ID if not provided
57 | req.ID = lo.Ternary(req.ID == "", g.NewTsID("sql"), req.ID)
58 |
59 | resp := NewResponse(req)
60 |
61 | if err = req.Validate(reqCheckConnection, reqCheckQuery); err != nil {
62 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
63 | }
64 |
65 | status202 := func(query *state.Query) {
66 | resp.Status = 202 // when status is 202, follow request with header "X-Request-Continue"
67 | resp.Payload = g.ToMap(query)
68 | resp.Header.Set("X-Request-Status", string(query.Status))
69 | }
70 |
71 | query := req.Project.NewQuery(context.Background())
72 | query.Conn = req.Connection
73 | query.Database = req.Database
74 | query.Text = req.Query
75 | query.ID = req.ID
76 |
77 | query.Limit = cast.ToInt(req.echoCtx.QueryParam("limit"))
78 | if query.Limit == 0 {
79 | query.Limit = 500
80 | }
81 |
82 | cont := req.Header.Get("X-Request-Continue") != ""
83 | query, err = state.SubmitOrGetQuery(query, cont)
84 | req.echoCtx.Set("query", query)
85 | if err != nil {
86 | return ErrJSON(http.StatusInternalServerError, err, "could not get process query")
87 | } else if query.IsGenerated && !cont {
88 | // send generated query to client
89 | status202(query)
90 | return resp.Make()
91 | }
92 |
93 | ticker := time.NewTicker(90 * time.Second)
94 | defer ticker.Stop()
95 |
96 | select {
97 | case <-query.Done:
98 | resp.ds = query.Stream
99 | err = query.ProcessResult()
100 | resp.Header.Set("X-Request-Status", string(query.Status))
101 | if err != nil {
102 | g.LogError(err)
103 | result := g.ToMap(query)
104 | result["err"] = g.ErrMsgSimple(err)
105 | resp.Payload = result
106 | return resp.Make()
107 | } else if query.Affected != -1 {
108 | resp.Payload = g.M("affected", query.Affected)
109 | return resp.Make()
110 | }
111 | return resp.MakeStreaming()
112 | case <-ticker.C:
113 | status202(query)
114 | }
115 |
116 | return resp.Make()
117 | }
118 |
--------------------------------------------------------------------------------
/server/routes_table.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "net/http"
5 | "strings"
6 |
7 | "github.com/flarco/g"
8 | "github.com/labstack/echo/v5"
9 | "github.com/samber/lo"
10 | "github.com/slingdata-io/sling-cli/core/dbio"
11 | "github.com/slingdata-io/sling-cli/core/dbio/database"
12 | "github.com/slingdata-io/sling-cli/core/dbio/iop"
13 | "github.com/spf13/cast"
14 | )
15 |
16 | func getTableColumns(c echo.Context) (err error) {
17 | req := NewRequest(c)
18 |
19 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
20 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
21 | }
22 |
23 | resp := NewResponse(req)
24 |
25 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
26 | tableColumns, err := c.GetTableColumns(&req.dbTable)
27 | if err != nil {
28 | err = g.Error(err, "could not get columns")
29 | return
30 | }
31 |
32 | columns := iop.Columns{
33 | {Name: "database_name", Type: iop.StringType},
34 | {Name: "schema_name", Type: iop.StringType},
35 | {Name: "table_name", Type: iop.StringType},
36 | {Name: "table_type", Type: iop.StringType},
37 | {Name: "column_id", Type: iop.IntegerType},
38 | {Name: "column_name", Type: iop.BoolType},
39 | {Name: "column_type", Type: iop.BoolType},
40 | }
41 | data = iop.NewDataset(columns)
42 | if req.CanRead(req.dbTable) || req.CanWrite(req.dbTable) {
43 | for _, column := range tableColumns {
44 | row := []any{
45 | req.Database,
46 | req.Schema,
47 | req.Table,
48 | nil,
49 | column.Position,
50 | column.Name,
51 | column.DbType,
52 | }
53 | data.Append(row)
54 | }
55 | }
56 |
57 | data.Sort(0, 1, 2, 4)
58 |
59 | // for middleware
60 | req.echoCtx.Set("data", &data)
61 |
62 | return
63 | }
64 |
65 | resp.data, err = ProcessRequest(req, rf)
66 | if err != nil {
67 | err = g.Error(err, "could not get columns")
68 | return
69 | }
70 |
71 | return resp.Make()
72 | }
73 |
74 | func getTableSelect(c echo.Context) (err error) {
75 | req := NewRequest(c)
76 |
77 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
78 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
79 | } else if !req.CanRead(req.dbTable) {
80 | return g.ErrJSON(http.StatusForbidden, g.Error("Not allowed"))
81 | }
82 |
83 | // construct SQL Query
84 | {
85 | conn, err := req.Project.GetConnObject(req.Connection, "")
86 | if err != nil {
87 | err = ErrJSON(http.StatusNotFound, err, "could not find connection: %s", req.Connection)
88 | return err
89 | }
90 |
91 | var preOptions, postOptions string
92 |
93 | // TODO: parse fields to ensure no SQL injection
94 | var fields []string
95 | var limit int
96 | whereMap := map[string]string{}
97 |
98 | for k, v := range req.echoCtx.QueryParams() {
99 | switch k {
100 | case ".columns":
101 | fields = strings.Split(v[0], ",")
102 | case ".limit":
103 | limit = cast.ToInt(v[0])
104 | limit = lo.Ternary(limit == 0, 100, limit)
105 | default:
106 | whereMap[k] = v[0]
107 | }
108 | }
109 |
110 | makeWhere := func() (ws string) {
111 | arr := []string{}
112 | for k, v := range whereMap {
113 | expr := g.F("%s=%s", k, v)
114 | arr = append(arr, expr)
115 | }
116 | // TODO: SQL Injection is possible, need to use bind vars
117 | return strings.Join(arr, " and ")
118 | }
119 |
120 | if limit > 0 { // For unlimited, specify -1
121 | switch conn.Type {
122 | case dbio.TypeDbSQLServer:
123 | preOptions = preOptions + g.F("top %d", limit)
124 | default:
125 | postOptions = postOptions + g.F("limit %d", limit)
126 | }
127 |
128 | // set for processQueryRequest
129 | req.echoCtx.QueryParams().Set("limit", cast.ToString(limit))
130 | }
131 |
132 | noFields := len(fields) == 0 || (len(fields) == 1 && fields[0] == "")
133 | noWhere := len(whereMap) == 0
134 |
135 | req.Query = g.R(
136 | "select{preOptions} {fields} from {table} where {where} {postOptions}",
137 | "fields", lo.Ternary(noFields, "*", strings.Join(fields, ", ")),
138 | "table", req.dbTable.FullName(),
139 | "where", lo.Ternary(noWhere, "1=1", makeWhere()),
140 | "preOptions", lo.Ternary(preOptions != "", " "+preOptions, ""),
141 | "postOptions", lo.Ternary(postOptions != "", " "+postOptions, ""),
142 | )
143 | }
144 |
145 | return processQueryRequest(req)
146 | }
147 |
148 | func getTableIndexes(c echo.Context) (err error) {
149 |
150 | req := NewRequest(c)
151 | resp := NewResponse(req)
152 |
153 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
154 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
155 | }
156 |
157 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
158 | return c.GetIndexes(req.dbTable.FullName())
159 | }
160 |
161 | resp.data, err = ProcessRequest(req, rf)
162 | if err != nil {
163 | err = ErrJSON(http.StatusBadRequest, err, "could not get table indexes")
164 | return
165 | }
166 |
167 | return resp.Make()
168 | }
169 |
170 | func getTableKeys(c echo.Context) (err error) {
171 | req := NewRequest(c)
172 | resp := NewResponse(req)
173 |
174 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
175 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
176 | }
177 |
178 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
179 | return c.GetPrimaryKeys(req.dbTable.FullName())
180 | }
181 |
182 | resp.data, err = ProcessRequest(req, rf)
183 | if err != nil {
184 | err = ErrJSON(http.StatusBadRequest, err, "could not get table keys")
185 | return
186 | }
187 |
188 | return resp.Make()
189 | }
190 |
191 | func postTableInsert(c echo.Context) (err error) {
192 | req := NewRequest(c)
193 | resp := NewResponse(req)
194 |
195 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
196 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
197 | } else if !req.CanWrite(req.dbTable) {
198 | return g.ErrJSON(http.StatusForbidden, g.Error("Not allowed"))
199 | }
200 |
201 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
202 |
203 | bulk := req.echoCtx.QueryParam(".bulk")
204 |
205 | ds, err := req.GetDatastream()
206 | if err != nil {
207 | err = g.Error(err, "could not get datastream")
208 | return
209 | }
210 |
211 | if req.echoCtx.QueryParam("bulk") == "true" {
212 | _ = bulk
213 | // TODO: bulk loading option
214 | // df, err := iop.MakeDataFlow(ds.Split()...)
215 | // if err != nil {
216 | // err = g.Error(err, "could not make dataflow")
217 | // return
218 | // }
219 | }
220 |
221 | ctx := req.echoCtx.Request().Context()
222 | err = c.BeginContext(ctx)
223 | if err != nil {
224 | err = g.Error(err, "could not begin transaction")
225 | return
226 | }
227 |
228 | count, err := c.InsertBatchStream(req.dbTable.FullName(), ds)
229 | if err != nil {
230 | err = g.Error(err, "could not insert into table")
231 | return
232 | }
233 |
234 | err = c.Commit()
235 | if err != nil {
236 | err = g.Error(err, "could not commit transaction")
237 | return
238 | }
239 |
240 | resp.Payload = g.M("affected", count)
241 |
242 | return
243 | }
244 |
245 | _, err = ProcessRequest(req, rf)
246 | if err != nil {
247 | err = ErrJSON(http.StatusBadRequest, err, "could not get process request")
248 | return
249 | }
250 |
251 | return resp.Make()
252 | }
253 |
254 | func postTableUpsert(c echo.Context) (err error) {
255 | req := NewRequest(c)
256 | resp := NewResponse(req)
257 | resp.Status = http.StatusNotImplemented
258 | resp.Payload = g.M("error", "Not-Implemented")
259 | return resp.Make()
260 |
261 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
262 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
263 | } else if !req.CanWrite(req.dbTable) {
264 | return g.ErrJSON(http.StatusForbidden, g.Error("Not allowed"))
265 | }
266 |
267 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
268 |
269 | bulk := req.echoCtx.QueryParam("bulk")
270 |
271 | ds, err := req.GetDatastream()
272 | if err != nil {
273 | err = g.Error(err, "could not get datastream")
274 | return
275 | }
276 |
277 | if req.echoCtx.QueryParam("bulk") == "true" {
278 | _ = bulk
279 | // TODO: bulk loading option
280 | // df, err := iop.MakeDataFlow(ds.Split()...)
281 | // if err != nil {
282 | // err = g.Error(err, "could not make dataflow")
283 | // return
284 | // }
285 | }
286 |
287 | ctx := req.echoCtx.Request().Context()
288 | err = c.BeginContext(ctx)
289 | if err != nil {
290 | err = g.Error(err, "could not begin transaction")
291 | return
292 | }
293 |
294 | // TODO: add c.UpsertBatchStream
295 | count, err := c.InsertBatchStream(req.dbTable.FullName(), ds)
296 | if err != nil {
297 | err = g.Error(err, "could not insert into table")
298 | return
299 | }
300 |
301 | err = c.Commit()
302 | if err != nil {
303 | err = g.Error(err, "could not commit transaction")
304 | return
305 | }
306 |
307 | resp.Payload = g.M("affected", count)
308 |
309 | return
310 | }
311 |
312 | _, err = ProcessRequest(req, rf)
313 | if err != nil {
314 | err = ErrJSON(http.StatusBadRequest, err, "could not get process request")
315 | return
316 | }
317 |
318 | return resp.Make()
319 | }
320 |
321 | func patchTableUpdate(c echo.Context) (err error) {
322 | req := NewRequest(c)
323 | resp := NewResponse(req)
324 | resp.Status = http.StatusNotImplemented
325 | resp.Payload = g.M("error", "Not-Implemented")
326 | return resp.Make()
327 |
328 | if err = req.Validate(reqCheckConnection, reqCheckSchema, reqCheckTable); err != nil {
329 | return ErrJSON(http.StatusBadRequest, err, "invalid request")
330 | } else if !req.CanWrite(req.dbTable) {
331 | return g.ErrJSON(http.StatusForbidden, g.Error("Not allowed"))
332 | }
333 |
334 | rf := func(c database.Connection, req Request) (data iop.Dataset, err error) {
335 | bulk := req.echoCtx.QueryParam("bulk")
336 |
337 | ds, err := req.GetDatastream()
338 | if err != nil {
339 | err = g.Error(err, "could not get datastream")
340 | return
341 | }
342 |
343 | if req.echoCtx.QueryParam("bulk") == "true" {
344 | _ = bulk
345 | _ = ds
346 | // TODO: bulk loading option
347 | // df, err := iop.MakeDataFlow(ds.Split()...)
348 | // if err != nil {
349 | // err = g.Error(err, "could not make dataflow")
350 | // return
351 | // }
352 | }
353 |
354 | ctx := req.echoCtx.Request().Context()
355 | err = c.BeginContext(ctx)
356 | if err != nil {
357 | err = g.Error(err, "could not begin transaction")
358 | return
359 | }
360 |
361 | // TODO: add c.UpdateBatchStream
362 | count, err := c.InsertBatchStream(req.dbTable.FullName(), ds)
363 | if err != nil {
364 | err = g.Error(err, "could not insert into table")
365 | return
366 | }
367 |
368 | err = c.Commit()
369 | if err != nil {
370 | err = g.Error(err, "could not commit transaction")
371 | return
372 | }
373 |
374 | data.Columns = iop.Columns{{Name: "affected", Type: iop.IntegerType}}
375 | data.Append([]any{count})
376 |
377 | return
378 | }
379 |
380 | resp.data, err = ProcessRequest(req, rf)
381 | if err != nil {
382 | err = ErrJSON(http.StatusBadRequest, err, "could not get process request")
383 | return
384 | }
385 |
386 | return resp.Make()
387 | }
388 |
--------------------------------------------------------------------------------
/server/server.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "net/http"
5 | "os"
6 | "time"
7 |
8 | "github.com/dbrest-io/dbrest/state"
9 | "github.com/flarco/g"
10 | "github.com/labstack/echo/v5"
11 | "github.com/labstack/echo/v5/middleware"
12 | )
13 |
14 | // Server is the main server
15 | type Server struct {
16 | Port string
17 | EchoServer *echo.Echo
18 | StartTime time.Time
19 | }
20 |
21 | func NewServer() (s *Server) {
22 | s = &Server{EchoServer: echo.New(), Port: "1323"}
23 | if port := os.Getenv("PORT"); port != "" {
24 | s.Port = port
25 | }
26 |
27 | // add routes
28 | for _, route := range StandardRoutes {
29 | route.Middlewares = append(route.Middlewares, middleware.Logger())
30 | route.Middlewares = append(route.Middlewares, middleware.Recover())
31 | s.EchoServer.AddRoute(route)
32 | }
33 |
34 | // cors
35 | s.EchoServer.Use(middleware.CORSWithConfig(middleware.CORSConfig{
36 | // AllowOrigins: []string{"http://localhost:1323"},
37 | // AllowCredentials: true,
38 | // AllowHeaders: []string{"*"},
39 | AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, "X-Request-ID", "X-Request-Columns", "X-Request-Continue", "X-Project-ID", "access-control-allow-origin", "access-control-allow-headers"},
40 | AllowOriginFunc: func(origin string) (bool, error) {
41 | return true, nil
42 | },
43 | }))
44 |
45 | return
46 | }
47 |
48 | func (s *Server) Start() {
49 | s.StartTime = time.Now()
50 | if err := s.EchoServer.Start(":" + s.Port); err != http.ErrServerClosed {
51 | g.LogFatal(g.Error(err, "could not start server"))
52 | }
53 | }
54 |
55 | func (s *Server) Hostname() string {
56 | return g.F("http://localhost:%s", s.Port)
57 | }
58 |
59 | func (s *Server) Close() {
60 | state.CloseConnections()
61 | }
62 |
--------------------------------------------------------------------------------
/server/server_functions.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "github.com/flarco/g"
5 | "github.com/labstack/echo/v5"
6 | )
7 |
8 | // ErrJSON returns to the echo.Context as JSON formatted
9 | func ErrJSON(HTTPStatus int, err error, args ...interface{}) error {
10 | msg := g.ArgsErrMsg(args...)
11 | g.LogError(err)
12 | if msg == "" {
13 | msg = g.ErrMsg(err)
14 | } else if g.ErrMsg(err) != "" {
15 | msg = g.F("%s [%s]", msg, g.ErrMsg(err))
16 | }
17 | return echo.NewHTTPError(HTTPStatus, g.M("error", msg))
18 | }
19 |
--------------------------------------------------------------------------------
/server/server_test.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "os"
5 | "path"
6 | "strings"
7 | "testing"
8 | "time"
9 |
10 | "github.com/dbrest-io/dbrest/env"
11 | "github.com/dbrest-io/dbrest/state"
12 | "github.com/flarco/g"
13 | "github.com/flarco/g/net"
14 | "github.com/labstack/echo/v5"
15 | "github.com/slingdata-io/sling-cli/core/dbio/database"
16 | "github.com/spf13/cast"
17 | "github.com/stretchr/testify/assert"
18 | )
19 |
20 | /*
21 | roles
22 | token
23 | Routes
24 | */
25 |
26 | var (
27 | headers = map[string]string{
28 | "Accept": "application/json",
29 | "Content-Type": "application/json",
30 | }
31 | testConnName = "SQLITE_TEST"
32 | testFolder = "./test"
33 | testDbURL = "sqlite://./test.db"
34 | testSchema = ""
35 | testTable = ""
36 | testID = "12345"
37 | tokenRW = ""
38 | tokenR = ""
39 | tokenW = ""
40 | randomRow = func() (rec map[string]any) { return }
41 | )
42 |
43 | func TestServer(t *testing.T) {
44 | // set up db
45 | deleteTestDB()
46 | defer deleteTestDB()
47 | err := createTestDB()
48 | if !assert.NoError(t, err) {
49 | return
50 | }
51 |
52 | os.Setenv(testConnName, testDbURL)
53 | os.MkdirAll(testFolder, 0777)
54 | ef := env.LoadDbRestEnvFile(path.Join(testFolder, "env.yaml"))
55 | ef.Connections[testConnName] = g.M("url", testDbURL)
56 | ef.WriteEnvFile()
57 |
58 | // start server
59 | s := NewServer()
60 | s.Port = "1456"
61 | go s.Start()
62 | defer s.Close()
63 |
64 | // test default project
65 | env.HomeDir = testFolder
66 | projectDefault := state.DefaultProject()
67 | testServer(t, s, projectDefault)
68 |
69 | // test specific project
70 | project := state.NewProject("test", testFolder, false)
71 | headers["X-Project-ID"] = project.ID
72 | testServer(t, s, project)
73 | }
74 |
75 | func testServer(t *testing.T, s *Server, project *state.Project) {
76 | var err error
77 |
78 | // set roles & tokens
79 | setTestRoles(project)
80 | setTestToken(project)
81 | headers["Authorization"] = tokenRW
82 |
83 | // project.LoadTokens(true)
84 | project.LoadRoles(true)
85 |
86 | time.Sleep(time.Second)
87 |
88 | makeURL := func(route echo.Route) string {
89 | url := g.F("%s%s", s.Hostname(), route.Path)
90 | url = strings.ReplaceAll(url, ":connection", testConnName)
91 | url = strings.ReplaceAll(url, ":schema", testSchema)
92 | url = strings.ReplaceAll(url, ":table", testTable)
93 | url = strings.ReplaceAll(url, ":id", testID)
94 | return url
95 | }
96 |
97 | // Test RW
98 | missingTests := []string{}
99 | for _, route := range StandardRoutes {
100 | if t.Failed() {
101 | break
102 | }
103 |
104 | g.Info("Testing route: %s with TokenRW", route.Name)
105 |
106 | respMap := map[string]any{}
107 | respArr := []map[string]any{}
108 |
109 | url := makeURL(route)
110 |
111 | msg := g.F("%s => %s %s", route.Name, route.Method, url)
112 |
113 | switch route.Name {
114 | case "getStatus":
115 | resp, respBytes, err := net.ClientDo(route.Method, url, nil, headers)
116 | assert.NoError(t, err, msg)
117 | assert.Less(t, resp.StatusCode, 300, msg)
118 | assert.Equal(t, "dbREST dev", string(respBytes), msg)
119 | case "getConnections", "getConnectionDatabases", "getConnectionSchemas", "getConnectionTables", "getConnectionColumns", "getSchemaTables", "getSchemaColumns", "getTableColumns", "getTableSelect", "getTableKeys":
120 | resp, respBytes, err := net.ClientDo(route.Method, url, nil, headers)
121 | g.Unmarshal(string(respBytes), &respArr)
122 | assert.NoError(t, err, msg)
123 | assert.Less(t, resp.StatusCode, 300, msg)
124 | assert.Greater(t, len(respArr), 0, msg)
125 | g.Debug(" got %d rows", len(respArr))
126 |
127 | if route.Name == "getConnectionTables" && len(respArr) > 0 {
128 | for _, row := range respArr {
129 | testSchema = cast.ToString(row["schema_name"])
130 | testTable = cast.ToString(row["table_name"])
131 | if !g.In(testSchema, "information_schema", "pg_catalog") {
132 | break // pick a good test table
133 | }
134 | }
135 | }
136 | case "submitSQL_ID":
137 | // delay so we can cancel
138 | go func() {
139 | sql := strings.NewReader(longQuery)
140 | resp, respBytes, err := net.ClientDo(route.Method, url, sql, headers)
141 | g.Unmarshal(string(respBytes), &respMap)
142 | assert.NoError(t, err, msg)
143 | assert.Less(t, resp.StatusCode, 300, msg)
144 | assert.NotEmpty(t, respMap["err"], msg)
145 | }()
146 | time.Sleep(100 * time.Millisecond)
147 | case "cancelSQL":
148 | // cancel delayed query
149 | resp, respBytes, err := net.ClientDo(route.Method, url, nil, headers)
150 | g.Unmarshal(string(respBytes), &respArr)
151 | assert.NoError(t, err, msg)
152 | assert.Less(t, resp.StatusCode, 300, msg)
153 | case "submitSQL":
154 | sql := strings.NewReader("select 1 as a, 2 as b")
155 | resp, respBytes, err := net.ClientDo(route.Method, url, sql, headers)
156 | g.Unmarshal(string(respBytes), &respArr)
157 | assert.NoError(t, err, msg)
158 | assert.Less(t, resp.StatusCode, 300, msg)
159 | assert.Greater(t, len(respArr), 0, msg)
160 | g.Debug(" got %d rows", len(respArr))
161 | case "tableInsert":
162 | recs := []map[string]any{}
163 | for i := 0; i < 10; i++ {
164 | recs = append(recs, randomRow())
165 | }
166 | payload := strings.NewReader(g.Marshal(recs))
167 | resp, respBytes, err := net.ClientDo(route.Method, url, payload, headers)
168 | g.Unmarshal(string(respBytes), &respMap)
169 | assert.NoError(t, err, msg)
170 | assert.Less(t, resp.StatusCode, 300, msg)
171 | assert.EqualValues(t, respMap["affected"], len(recs))
172 | default:
173 | missingTests = append(missingTests, route.Name)
174 | }
175 | }
176 |
177 | if len(missingTests) > 0 {
178 | g.Warn("No test for routes: %s", strings.Join(missingTests, ", "))
179 | }
180 |
181 | // Test R
182 | headers["Authorization"] = tokenR
183 | for _, route := range StandardRoutes {
184 | if t.Failed() {
185 | break
186 | } else if !g.In(route.Name, "getTableSelect", "tableInsert", "submitSQL") {
187 | continue
188 | }
189 |
190 | g.Info("Testing route: %s with TokenR", route.Name)
191 |
192 | url := makeURL(route)
193 | msg := g.F("%s => %s %s", route.Name, route.Method, url)
194 |
195 | switch route.Name {
196 | case "getTableSelect":
197 | // we should have access to place
198 | testTable = "place"
199 | url = makeURL(route)
200 | _, _, err = net.ClientDo(route.Method, url, nil, headers)
201 | assert.NoError(t, err, msg)
202 |
203 | // we should not have access to place2
204 | testTable = "place2"
205 | url = makeURL(route)
206 | _, _, err = net.ClientDo(route.Method, url, nil, headers)
207 | assert.Error(t, err, msg)
208 | case "tableInsert":
209 | // we should not have write access to any tables
210 | testTable = "place2"
211 | url = makeURL(route)
212 | recs := []map[string]any{}
213 | for i := 0; i < 10; i++ {
214 | recs = append(recs, randomRow())
215 | }
216 | payload := strings.NewReader(g.Marshal(recs))
217 | _, _, err = net.ClientDo(route.Method, url, payload, headers)
218 | assert.Error(t, err, msg)
219 | case "submitSQL":
220 | // we should not have sql access
221 | sql := strings.NewReader("select 1 as a, 2 as b")
222 | _, _, err := net.ClientDo(route.Method, url, sql, headers)
223 | assert.Error(t, err, msg)
224 | }
225 | }
226 |
227 | // Test W
228 | headers["Authorization"] = tokenW
229 | for _, route := range StandardRoutes {
230 | if t.Failed() {
231 | break
232 | } else if !g.In(route.Name, "getTableSelect", "tableInsert", "submitSQL") {
233 | continue
234 | }
235 |
236 | g.Info("Testing route: %s with TokenW", route.Name)
237 |
238 | url := makeURL(route)
239 | msg := g.F("%s => %s %s", route.Name, route.Method, url)
240 |
241 | switch route.Name {
242 | case "getTableSelect":
243 | // we should not have access to any table
244 | testTable = "place"
245 | url = makeURL(route)
246 | _, _, err = net.ClientDo(route.Method, url, nil, headers)
247 | assert.Error(t, err, msg)
248 | case "tableInsert":
249 | // we should have write access to place
250 | testTable = "place"
251 | url = makeURL(route)
252 | recs := []map[string]any{}
253 | for i := 0; i < 10; i++ {
254 | recs = append(recs, randomRow())
255 | }
256 | payload := strings.NewReader(g.Marshal(recs))
257 | _, _, err = net.ClientDo(route.Method, url, payload, headers)
258 | assert.NoError(t, err, msg)
259 |
260 | testTable = "place2"
261 | url = makeURL(route)
262 | payload = strings.NewReader(g.Marshal(recs))
263 | _, _, err = net.ClientDo(route.Method, url, payload, headers)
264 | assert.Error(t, err, msg)
265 | case "submitSQL":
266 | // we should not have sql access
267 | sql := strings.NewReader("select 1 as a, 2 as b")
268 | _, _, err := net.ClientDo(route.Method, url, sql, headers)
269 | assert.Error(t, err, msg)
270 | }
271 | }
272 | }
273 |
274 | var longQuery = `
275 | -- https://dba.stackexchange.com/questions/203545/write-a-slow-sqlite-query-to-test-timeout
276 | WITH RECURSIVE r(i) AS (
277 | VALUES(0)
278 | UNION ALL
279 | SELECT i FROM r
280 | LIMIT 1000000
281 | )
282 | SELECT i FROM r WHERE i = 1`
283 |
284 | func createTestDB() (err error) {
285 | conn, err := database.NewConn(testDbURL)
286 | if err != nil {
287 | return err
288 | }
289 |
290 | _, err = conn.Exec(`CREATE TABLE "place" ("id" int, "country" varchar(255), "city" varchar(255), "telcode" bigint, primary key (id))`)
291 | if err != nil {
292 | return err
293 | }
294 |
295 | _, err = conn.Exec(`CREATE INDEX idx_country_city ON place(country, city)`)
296 | if err != nil {
297 | return err
298 | }
299 |
300 | _, err = conn.Exec(`CREATE TABLE "place2" ("id" int, "country" varchar(255), "city" varchar(255), "telcode" bigint, primary key (id))`)
301 | if err != nil {
302 | return err
303 | }
304 |
305 | conn.Close()
306 |
307 | countries := []string{
308 | "Canada",
309 | "USA",
310 | "Brazil",
311 | "Russia",
312 | "India",
313 | }
314 |
315 | cities := []string{
316 | "Big City",
317 | "Small City",
318 | "Tiny City",
319 | }
320 |
321 | randomRow = func() (rec map[string]any) {
322 | return map[string]any{
323 | "id": g.RandInt(10000),
324 | "country": countries[g.RandInt(5)],
325 | "city": cities[g.RandInt(3)],
326 | "telcode": 100000000 + g.RandInt(900000000),
327 | }
328 | }
329 |
330 | return
331 | }
332 |
333 | func deleteTestDB() { os.Remove("./test.db") }
334 |
335 | func setTestRoles(project *state.Project) {
336 | testRoleRW := state.Role{}
337 | testRoleR := state.Role{}
338 | testRoleW := state.Role{}
339 |
340 | connName := strings.ToLower(testConnName)
341 | testRoleRW[connName] = state.Grant{
342 | AllowRead: []string{"*"},
343 | AllowWrite: []string{"*"},
344 | AllowSQL: state.AllowSQLAny,
345 | }
346 | testRoleR[connName] = state.Grant{
347 | AllowRead: []string{"main.place"},
348 | AllowWrite: []string{},
349 | AllowSQL: state.AllowSQLDisable,
350 | }
351 | testRoleW[connName] = state.Grant{
352 | AllowRead: []string{},
353 | AllowWrite: []string{"main.place"},
354 | AllowSQL: state.AllowSQLDisable,
355 | }
356 |
357 | project.Roles = state.RoleMap{
358 | "role_rw": testRoleRW,
359 | "role_r": testRoleR,
360 | "role_w": testRoleW,
361 | }
362 | }
363 |
364 | func setTestToken(project *state.Project) {
365 | // project.TokenFile = path.Join(".tokens.test")
366 | token := state.NewToken([]string{"role_rw"})
367 | err := project.TokenAdd("token_rw", token)
368 | g.LogFatal(err)
369 | tokenRW = token.Token
370 |
371 | token = state.NewToken([]string{"role_r"})
372 | err = project.TokenAdd("token_r", token)
373 | g.LogFatal(err)
374 | tokenR = token.Token
375 |
376 | token = state.NewToken([]string{"role_w"})
377 | err = project.TokenAdd("token_w", token)
378 | g.LogFatal(err)
379 | tokenW = token.Token
380 | }
381 |
--------------------------------------------------------------------------------
/state/grants.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | import (
4 | "github.com/flarco/g"
5 | "github.com/slingdata-io/sling-cli/core/dbio/connection"
6 | "github.com/slingdata-io/sling-cli/core/dbio/database"
7 | )
8 |
9 | type Grant struct {
10 | // AllowRead lists the schema/tables that are allowed to be read from
11 | AllowRead []string `json:"allow_read" yaml:"allow_read"`
12 | // AllowWrite lists the schema/tables that are allowed to be written to
13 | AllowWrite []string `json:"allow_write" yaml:"allow_write"`
14 | // AllowSQL shows whether a
15 | AllowSQL AllowSQLValue `json:"allow_sql" yaml:"allow_sql"`
16 | }
17 |
18 | // Permissions is a map of all objects for one connection
19 | type Permissions map[string]Permission
20 |
21 | type Permission string
22 |
23 | const (
24 | PermissionNone Permission = "none"
25 | PermissionRead Permission = "read"
26 | PermissionWrite Permission = "write"
27 | PermissionReadWrite Permission = "read_write"
28 | )
29 |
30 | func (p Permission) CanRead() bool {
31 | return p == PermissionRead || p == PermissionReadWrite
32 | }
33 |
34 | func (p Permission) CanWrite() bool {
35 | return p == PermissionWrite || p == PermissionReadWrite
36 | }
37 |
38 | type AllowSQLValue string
39 |
40 | const (
41 | AllowSQLDisable AllowSQLValue = "disable"
42 | AllowSQLAny AllowSQLValue = "any"
43 | // AllowSQLOnlySelect AllowSQLValue = "only_select"
44 | )
45 |
46 | func (gt Grant) GetReadable(conn connection.Connection) (tables []database.Table) {
47 | for _, t := range gt.AllowRead {
48 | table, err := database.ParseTableName(t, conn.Type)
49 | if err != nil {
50 | g.Warn("could not parse table entry: %s", t)
51 | continue
52 | }
53 | tables = append(tables, table)
54 | }
55 | return
56 | }
57 |
58 | func (gt Grant) GetWritable(conn connection.Connection) (tables []database.Table) {
59 | for _, t := range gt.AllowWrite {
60 | table, err := database.ParseTableName(t, conn.Type)
61 | if err != nil {
62 | g.Warn("could not parse table entry: %s", t)
63 | continue
64 | }
65 | tables = append(tables, table)
66 | }
67 | return
68 | }
69 |
--------------------------------------------------------------------------------
/state/project.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | import (
4 | "context"
5 | "os"
6 | "path"
7 | "strings"
8 | "sync"
9 | "time"
10 |
11 | "github.com/dbrest-io/dbrest/env"
12 | "github.com/flarco/g"
13 | "github.com/slingdata-io/sling-cli/core/dbio/connection"
14 | "github.com/slingdata-io/sling-cli/core/dbio/database"
15 | "github.com/spf13/cast"
16 | "gopkg.in/yaml.v3"
17 | )
18 |
19 | var DefaultProjectID = "default"
20 |
21 | var Projects = map[string]*Project{}
22 |
23 | type Project struct {
24 | ID string
25 | Directory string
26 |
27 | Connections map[string]*Connection
28 | Queries map[string]*Query
29 | Tokens TokenMap
30 | TokenValues map[string]Token
31 |
32 | Roles RoleMap
33 | NoRestriction bool
34 |
35 | EnvFile string
36 | TokenFile string
37 | RolesFile string
38 |
39 | mux sync.Mutex
40 |
41 | lastLoadedConns time.Time
42 | lastLoadedRoles time.Time
43 | lastLoadedTokens time.Time
44 | }
45 |
46 | func DefaultProject() (proj *Project) {
47 | if DefaultProjectID == "" {
48 | return nil
49 | }
50 |
51 | if proj = LoadProject(DefaultProjectID); proj != nil {
52 | return proj
53 | }
54 |
55 | noRestriction := false
56 | if val := os.Getenv("DBREST_NO_RESTRICTION"); val != "" {
57 | noRestriction = cast.ToBool(val)
58 | }
59 |
60 | return NewProject(DefaultProjectID, env.HomeDir, noRestriction)
61 | }
62 |
63 | func NewProject(id, directory string, noRestriction bool) (proj *Project) {
64 | mux.Lock()
65 | defer mux.Unlock()
66 |
67 | p := &Project{
68 | ID: id,
69 | Directory: directory,
70 | Connections: map[string]*Connection{},
71 | Queries: map[string]*Query{},
72 | Tokens: TokenMap{},
73 | TokenValues: map[string]Token{},
74 | Roles: RoleMap{},
75 | NoRestriction: noRestriction,
76 | EnvFile: path.Join(directory, "env.yaml"),
77 | TokenFile: path.Join(directory, ".tokens"),
78 | RolesFile: path.Join(directory, "roles.yaml"),
79 | mux: sync.Mutex{},
80 | lastLoadedRoles: time.Unix(0, 0),
81 | lastLoadedTokens: time.Unix(0, 0),
82 | }
83 |
84 | p.LoadTokens(true)
85 | p.LoadRoles(true)
86 | p.LoadConnections(true)
87 |
88 | Projects[id] = p
89 |
90 | return p
91 | }
92 |
93 | func LoadProject(id string) (proj *Project) {
94 | mux.Lock()
95 | defer mux.Unlock()
96 |
97 | if p, ok := Projects[id]; ok {
98 | p.LoadTokens(false)
99 | p.LoadRoles(false)
100 | p.LoadConnections(false)
101 |
102 | return p
103 | }
104 |
105 | return nil
106 | }
107 |
108 | func (p *Project) LoadRoles(force bool) (err error) {
109 | if !(force || time.Since(p.lastLoadedRoles) > (5*time.Second)) {
110 | return
111 | }
112 |
113 | if g.PathExists(p.RolesFile) {
114 | var roles RoleMap
115 | rolesB, _ := os.ReadFile(p.RolesFile)
116 | err = yaml.Unmarshal(rolesB, &roles)
117 | if err != nil {
118 | return g.Error(err, "could not load roles")
119 | }
120 |
121 | // make keys upper case
122 | for name, r := range roles {
123 | role := Role{}
124 | for k, grant := range r {
125 | role[strings.ToLower(k)] = grant
126 | }
127 | p.Roles[strings.ToLower(name)] = role
128 | }
129 | p.lastLoadedRoles = time.Now()
130 | }
131 | return
132 | }
133 |
134 | func (p *Project) GetRoleMap(roles []string) (rm RoleMap) {
135 | rm = RoleMap{}
136 | for _, rn := range roles {
137 | rn = strings.ToLower(rn)
138 | if role, ok := p.Roles[rn]; ok {
139 | rm[rn] = role
140 | }
141 | }
142 | return
143 | }
144 |
145 | func (p *Project) GetConnObject(connName, databaseName string) (connObj connection.Connection, err error) {
146 | mux.Lock()
147 | connName = strings.ToLower(connName)
148 | c, ok := p.Connections[connName]
149 | mux.Unlock()
150 | if !ok {
151 | err = g.Error("could not find conn %s", connName)
152 | return
153 | }
154 |
155 | if databaseName == "" {
156 | // default
157 | return c.Conn, nil
158 | }
159 |
160 | // create new connection with specific database
161 | data := g.M()
162 | for k, v := range c.Conn.Data {
163 | data[k] = v
164 | }
165 | if databaseName != "" {
166 | data["database"] = strings.ToLower(databaseName)
167 | }
168 | delete(data, "url")
169 | delete(data, "schema")
170 | connObj, err = connection.NewConnectionFromMap(g.M("name", c.Conn.Name, "data", data, "type", c.Conn.Type))
171 | if err != nil {
172 | err = g.Error(err, "could not load connection %s", c.Conn.Name)
173 | return
174 | }
175 | return
176 | }
177 |
178 | func (p *Project) LoadConnections(force bool) (err error) {
179 | p.mux.Lock()
180 | defer p.mux.Unlock()
181 |
182 | if !(time.Since(p.lastLoadedConns).Seconds() > 2 || force) {
183 | return
184 | }
185 |
186 | p.Connections = map[string]*Connection{}
187 |
188 | var connEntries []connection.ConnEntry
189 | if p.ID == DefaultProjectID {
190 | // get all connections
191 | connEntries = connection.GetLocalConns(force)
192 | } else {
193 | // need to load for the project only
194 | m := g.M()
195 | g.JSONConvert(env.LoadEnvFile(p.EnvFile), &m)
196 | profileConns, err := connection.ReadConnections(m)
197 | if err != nil {
198 | return g.Error(err, "could not read project env connections")
199 | }
200 |
201 | for name, pConn := range profileConns {
202 | entry := connection.ConnEntry{
203 | Name: name,
204 | Connection: pConn,
205 | Source: "project env yaml",
206 | }
207 | connEntries = append(connEntries, entry)
208 | }
209 | }
210 |
211 | for _, entry := range connEntries {
212 | if !entry.Connection.Type.IsDb() {
213 | continue
214 | }
215 |
216 | name := strings.ToLower(strings.ReplaceAll(entry.Name, "/", "_"))
217 | p.Connections[name] = &Connection{
218 | Conn: entry.Connection,
219 | Source: entry.Source,
220 | Props: map[string]string{},
221 | }
222 | }
223 |
224 | p.lastLoadedConns = time.Now()
225 |
226 | return nil
227 | }
228 |
229 | // SchemaAll returns schema.*
230 | // notation for all tables in a schema
231 | func (p *Project) SchemaAll(connection, schema string) (table database.Table) {
232 | conn, err := p.GetConnObject(connection, "")
233 | if err != nil {
234 | return database.Table{}
235 | }
236 | table, _ = database.ParseTableName(schema+".*", conn.Type)
237 | return table
238 | }
239 |
240 | func (p *Project) GetConnInstance(connName, databaseName string) (conn database.Connection, err error) {
241 | err = p.LoadConnections(false)
242 | if err != nil {
243 | err = g.Error(err, "could not load connections")
244 | return
245 | }
246 |
247 | mux.Lock()
248 | connName = strings.ToLower(connName)
249 | c := p.Connections[connName]
250 | mux.Unlock()
251 |
252 | connObj, err := p.GetConnObject(connName, databaseName)
253 | if err != nil {
254 | err = g.Error(err, "could not load connection %s", connName)
255 | return
256 | }
257 |
258 | // connect or use pool
259 | os.Setenv("USE_POOL", "TRUE")
260 |
261 | // init connection
262 | conn, err = connObj.AsDatabase(true)
263 | if err != nil {
264 | err = g.Error(err, "could not initialize database connection '%s' / '%s' with provided credentials/url.", connName, databaseName)
265 | return
266 | }
267 |
268 | err = conn.Connect()
269 | if err != nil {
270 | err = g.Error(err, "could not connect with provided credentials/url")
271 | return
272 | }
273 | c.Props = conn.Props()
274 |
275 | // set SetMaxIdleConns
276 | // conn.Db().SetMaxIdleConns(2)
277 |
278 | return
279 | }
280 |
281 | func (p *Project) NewQuery(ctx context.Context) *Query {
282 | q := new(Query)
283 | q.Project = p.ID
284 | q.Affected = -1
285 | q.lastTouch = time.Now()
286 | q.Context = g.NewContext(ctx)
287 | q.Done = make(chan struct{})
288 | return q
289 | }
290 |
--------------------------------------------------------------------------------
/state/project_tokens.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | import (
4 | "os"
5 | "strings"
6 | "time"
7 |
8 | "github.com/flarco/g"
9 | "github.com/samber/lo"
10 | )
11 |
12 | // TokenMap is map of string to token
13 | type TokenMap map[string]Token
14 |
15 | type Token struct {
16 | Token string `json:"token"`
17 | Roles []string `json:"roles"`
18 | Disabled bool `json:"disabled"`
19 | IssuedAt time.Time `json:"issued_at"`
20 | }
21 |
22 | func (p *Project) LoadTokens(force bool) (err error) {
23 | if !(force || time.Since(p.lastLoadedTokens) > (5*time.Second)) {
24 | return
25 | }
26 |
27 | if !g.PathExists(p.TokenFile) {
28 | os.WriteFile(p.TokenFile, []byte("{}"), 0644)
29 | }
30 |
31 | bytes, _ := os.ReadFile(p.TokenFile)
32 | err = g.JSONUnmarshal(bytes, &p.Tokens)
33 | if err != nil {
34 | err = g.Error(err, "could not unmarshal token map")
35 | }
36 |
37 | // populate token values map
38 | for _, token := range p.Tokens {
39 | p.TokenValues[token.Token] = token
40 | }
41 |
42 | p.lastLoadedTokens = time.Now()
43 |
44 | return
45 | }
46 |
47 | func (p *Project) ResolveToken(value string) (token Token, ok bool) {
48 | p.mux.Lock()
49 | token, ok = p.TokenValues[value]
50 | p.mux.Unlock()
51 | return
52 | }
53 |
54 | func (p *Project) TokenGet(name string, token Token) (err error) {
55 | p.mux.Lock()
56 | p.Tokens[name] = token
57 | p.mux.Unlock()
58 |
59 | err = p.TokenSave()
60 | if err != nil {
61 | err = g.Error(err, "could not update token map")
62 | }
63 | return
64 | }
65 |
66 | func (p *Project) TokenAdd(name string, token Token) (err error) {
67 | // check roles
68 | roles := lo.Keys(p.Roles)
69 | if len(roles) == 0 {
70 | g.Warn("No roles have been defined. See https://docs.dbrest.io")
71 | return g.Error("No roles have been defined. Please create file %s", p.RolesFile)
72 | }
73 |
74 | for _, role := range token.Roles {
75 | role = strings.ToLower(role)
76 | if !lo.Contains(roles, role) {
77 | return g.Error("invalid role: %s. Available roles: %s", role, strings.Join(roles, ","))
78 | }
79 | }
80 |
81 | p.mux.Lock()
82 | p.Tokens[name] = token
83 | p.TokenValues[token.Token] = token
84 | p.mux.Unlock()
85 |
86 | err = p.TokenSave()
87 | if err != nil {
88 | err = g.Error(err, "could not update token map")
89 | }
90 |
91 | return
92 | }
93 |
94 | func (p *Project) TokenToggle(name string) (disabled bool, err error) {
95 | p.mux.Lock()
96 | token, ok := p.Tokens[name]
97 | if !ok {
98 | return disabled, g.Error("token %s does not exist", name)
99 | }
100 |
101 | token.Disabled = !token.Disabled
102 | disabled = token.Disabled
103 | p.Tokens[name] = token
104 | p.TokenValues[token.Token] = token
105 | p.mux.Unlock()
106 |
107 | err = p.TokenSave()
108 | if err != nil {
109 | err = g.Error(err, "could not update token map")
110 | }
111 |
112 | return
113 | }
114 |
115 | func (p *Project) TokenRemove(name string) (err error) {
116 | p.mux.Lock()
117 | token, ok := p.Tokens[name]
118 | if !ok {
119 | return g.Error("token %s does not exist", name)
120 | }
121 |
122 | delete(p.Tokens, name)
123 | delete(p.TokenValues, token.Token)
124 | p.mux.Unlock()
125 |
126 | err = p.TokenSave()
127 | if err != nil {
128 | err = g.Error(err, "could not update token map")
129 | }
130 | return
131 | }
132 |
133 | func (p *Project) TokenSave() (err error) {
134 | p.mux.Lock()
135 | defer p.mux.Unlock()
136 | err = os.WriteFile(p.TokenFile, []byte(g.Marshal(p.Tokens)), 0644)
137 | if err != nil {
138 | err = g.Error(err, "could not write token map")
139 | }
140 | return
141 | }
142 |
143 | func NewToken(roles []string) Token {
144 | return Token{
145 | Token: g.RandString(g.AlphaNumericRunes, 64),
146 | Roles: roles,
147 | Disabled: false,
148 | IssuedAt: time.Now(),
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/state/query.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | import (
4 | "database/sql/driver"
5 | "strings"
6 | "time"
7 |
8 | "github.com/flarco/g"
9 | "github.com/jmoiron/sqlx"
10 | "github.com/slingdata-io/sling-cli/core/dbio/database"
11 | "github.com/slingdata-io/sling-cli/core/dbio/iop"
12 | "gopkg.in/yaml.v3"
13 | )
14 |
15 | // Query represents a query
16 | type Query struct {
17 | ID string `json:"id" query:"id" gorm:"primaryKey"`
18 | Project string `json:"project" query:"project" gorm:"index"`
19 | Conn string `json:"conn" query:"conn" gorm:"index"`
20 | Database string `json:"database" query:"database" gorm:"index"`
21 | Text string `json:"text" query:"text"`
22 | Limit int `json:"limit" query:"limit" gorm:"-"` // -1 is unlimited
23 |
24 | Start int64 `json:"start" query:"start" gorm:"index:idx_start"`
25 | End int64 `json:"end" query:"end"`
26 | Status QueryStatus `json:"status" query:"status"`
27 | Err string `json:"err" query:"err"`
28 | Headers Headers `json:"headers" query:"headers" gorm:"headers"`
29 |
30 | UpdatedDt time.Time `json:"-" gorm:"autoUpdateTime"`
31 | Connection database.Connection `json:"-" gorm:"-"`
32 | Affected int64 `json:"affected" gorm:"-"`
33 | Result *sqlx.Rows `json:"-" gorm:"-"`
34 | Stream *iop.Datastream `json:"-" gorm:"-"`
35 | Done chan struct{} `json:"-" gorm:"-"`
36 | Error error `json:"-" gorm:"-"`
37 | Context *g.Context `json:"-" gorm:"-"`
38 | lastTouch time.Time `json:"-" gorm:"-"`
39 | IsGenerated bool `json:"-" gorm:"-"`
40 | }
41 |
42 | type QueryStatus string
43 |
44 | const QueryStatusCompleted QueryStatus = "completed"
45 | const QueryStatusFetched QueryStatus = "fetched"
46 | const QueryStatusCancelled QueryStatus = "cancelled"
47 | const QueryStatusErrored QueryStatus = "errored"
48 | const QueryStatusSubmitted QueryStatus = "submitted"
49 |
50 | type Headers []string
51 |
52 | // Scan scan value into Jsonb, implements sql.Scanner interface
53 | func (h *Headers) Scan(value interface{}) error {
54 | return g.JSONScanner(h, value)
55 | }
56 |
57 | // Value return json value, implement driver.Valuer interface
58 | func (h Headers) Value() (driver.Value, error) {
59 | return g.JSONValuer(h, "[]")
60 | }
61 |
62 | type Row []interface{}
63 |
64 | // Scan scan value into Jsonb, implements sql.Scanner interface
65 | func (r *Row) Scan(value interface{}) error {
66 | return g.JSONScanner(r, value)
67 | }
68 |
69 | // Value return json value, implement driver.Valuer interface
70 | func (r Row) Value() (driver.Value, error) {
71 | return g.JSONValuer(r, "[]")
72 | }
73 |
74 | type Rows [][]interface{}
75 |
76 | // Scan scan value into Jsonb, implements sql.Scanner interface
77 | func (r *Rows) Scan(value interface{}) error {
78 | return g.JSONScanner(r, value)
79 | }
80 |
81 | // Value return json value, implement driver.Valuer interface
82 | func (r Rows) Value() (driver.Value, error) {
83 | return g.JSONValuer(r, "[]")
84 | }
85 |
86 | func SubmitOrGetQuery(q *Query, cont bool) (query *Query, err error) {
87 | if cont {
88 |
89 | proj := LoadProject(q.Project)
90 | if proj == nil {
91 | return query, g.Error("unable to load project %s", q.Project)
92 | }
93 |
94 | // pick up where left off
95 | mux.Lock()
96 | var ok bool
97 | query, ok = proj.Queries[q.ID]
98 | if ok {
99 | query.lastTouch = time.Now()
100 | }
101 | mux.Unlock()
102 |
103 | if !ok {
104 | err = g.Error("could not find query %s to continue", q.ID)
105 | return
106 | }
107 | } else {
108 | err = q.prepare()
109 | if err != nil {
110 | err = g.Error(err, "could not prepare query")
111 | return
112 | }
113 | // submit
114 | go q.Submit()
115 | query = q
116 | }
117 |
118 | return
119 | }
120 |
121 | func (q *Query) Cancel() (err error) {
122 | id := q.ID
123 |
124 | proj := LoadProject(q.Project)
125 | if proj == nil {
126 | return g.Error("unable to load project %s", q.Project)
127 | }
128 |
129 | mux.Lock()
130 | q, ok := proj.Queries[id]
131 | mux.Unlock()
132 | if !ok {
133 | err = g.Error("could not find query %s", id)
134 | return
135 | }
136 |
137 | err = q.Close(true)
138 | if err != nil {
139 | err = g.Error(err, "could not close query %s", id)
140 | return
141 | }
142 |
143 | q.Status = QueryStatusCancelled
144 |
145 | mux.Lock()
146 | delete(proj.Queries, q.ID)
147 | mux.Unlock()
148 |
149 | return
150 | }
151 |
152 | func (q *Query) Submit() (err error) {
153 | defer func() { q.Done <- struct{}{} }()
154 |
155 | setError := func(err error) {
156 | q.Status = QueryStatusErrored
157 | q.Error = err
158 | q.Err = g.ErrMsg(err)
159 | q.End = time.Now().Unix()
160 | }
161 |
162 | q.Status = QueryStatusSubmitted
163 | q.Context = g.NewContext(q.Connection.Context().Ctx)
164 |
165 | sqls := database.ParseSQLMultiStatements(q.Text)
166 | if len(sqls) == 1 && q.isSelecting() {
167 | g.Debug("--------------------------------------------------------------------- submitting %s (selecting)", q.ID)
168 | q.Stream, err = q.Connection.StreamRowsContext(q.Context.Ctx, q.Text, g.M("limit", q.Limit))
169 | if err != nil {
170 | setError(err)
171 | err = g.Error(err, "could not execute query")
172 | return
173 | }
174 |
175 | q.Status = QueryStatusCompleted
176 | } else {
177 | g.Debug("--------------------------------------------------------------------- submitting %s (executing)", q.ID)
178 | _, err = q.Connection.NewTransaction(q.Context.Ctx)
179 | if err != nil {
180 | setError(err)
181 | err = g.Error(err, "could not start transaction")
182 | return err
183 | }
184 |
185 | defer q.Connection.Rollback()
186 | res, err := q.Connection.ExecMultiContext(q.Context.Ctx, q.Text)
187 | if err != nil {
188 | setError(err)
189 | err = g.Error(err, "could not execute queries")
190 | return err
191 | }
192 | err = q.Connection.Commit()
193 | if err != nil {
194 | setError(err)
195 | err = g.Error(err, "could not commit")
196 | return err
197 | }
198 |
199 | q.Status = QueryStatusCompleted
200 | q.Affected, _ = res.RowsAffected()
201 | }
202 |
203 | return
204 | }
205 |
206 | // processCustomReq looks at the text for yaml parsing
207 | func (q *Query) prepare() (err error) {
208 |
209 | // get connection
210 | proj := LoadProject(q.Project)
211 | if proj == nil {
212 | return g.Error("unable to load project %s", q.Project)
213 | }
214 |
215 | q.Connection, err = proj.GetConnInstance(q.Conn, q.Database)
216 | if err != nil {
217 | err = g.Error(err, "could not get conn %s", q.Conn)
218 | return
219 | }
220 |
221 | err = q.processCustomReq()
222 | if err != nil {
223 | err = g.Error(err, "could not get templatized sql")
224 | return
225 | }
226 |
227 | mux.Lock()
228 | proj.Queries[q.ID] = q
229 | mux.Unlock()
230 |
231 | q.Text = strings.TrimSuffix(q.Text, ";")
232 |
233 | return nil
234 | }
235 |
236 | func (q *Query) processCustomReq() (err error) {
237 |
238 | // see if analysis req
239 | if strings.HasPrefix(q.Text, "/*--") && strings.HasSuffix(q.Text, "--*/") {
240 | // is data request in yaml or json
241 | // /*--{"analysis":"field_count", "data": {...}} --*/
242 | // /*--{"metadata":"ddl_table", "data": {...}} --*/
243 | type analysisReq struct {
244 | Analysis string `json:"analysis" yaml:"analysis"`
245 | Metadata string `json:"metadata" yaml:"metadata"`
246 | Data map[string]interface{} `json:"data" yaml:"data"`
247 | }
248 |
249 | req := analysisReq{}
250 | body := strings.TrimSuffix(strings.TrimPrefix(q.Text, "/*--"), "--*/")
251 | err = yaml.Unmarshal([]byte(body), &req)
252 | if err != nil {
253 | err = g.Error(err, "could not parse yaml/json request")
254 | return
255 | }
256 |
257 | sql := ""
258 | switch {
259 | case req.Analysis != "":
260 | sql, err = q.Connection.GetAnalysis(req.Analysis, req.Data)
261 | case req.Metadata != "":
262 | template, ok := q.Connection.Template().Metadata[req.Metadata]
263 | if !ok {
264 | err = g.Error("metadata key '%s' not found", req.Metadata)
265 | }
266 | sql = g.Rm(template, req.Data)
267 | }
268 |
269 | if err != nil {
270 | err = g.Error(err, "could not execute query")
271 | return
272 | }
273 |
274 | q.Text = q.Text + "\n\n" + sql
275 | q.IsGenerated = true
276 | }
277 | return
278 | }
279 |
280 | // isSelecting detects whether a query is a SELECT query
281 | func (q *Query) isSelecting() bool {
282 | // Parse the SQL statements
283 | sqls := database.ParseSQLMultiStatements(q.Text)
284 |
285 | // Check each statement
286 | for _, sql := range sqls {
287 | if t, err := database.TrimSQLComments(sql); err == nil {
288 | sql = t
289 | }
290 | normalizedSQL := strings.ToLower(strings.TrimSpace(sql))
291 | if strings.HasPrefix(normalizedSQL, "create") || strings.HasPrefix(normalizedSQL, "insert") ||
292 | strings.HasPrefix(normalizedSQL, "update") || strings.HasPrefix(normalizedSQL, "delete") ||
293 | strings.HasPrefix(normalizedSQL, "drop") || strings.HasPrefix(normalizedSQL, "alter") ||
294 | strings.HasPrefix(normalizedSQL, "truncate") || strings.HasPrefix(normalizedSQL, "merge") ||
295 | strings.HasPrefix(normalizedSQL, "grant") || strings.HasPrefix(normalizedSQL, "revoke") {
296 | return false
297 | }
298 | if strings.HasPrefix(normalizedSQL, "select") ||
299 | strings.HasPrefix(normalizedSQL, "with") ||
300 | (strings.Contains(normalizedSQL, "select") && strings.Contains(normalizedSQL, "from")) {
301 | return true
302 | }
303 | }
304 |
305 | return false
306 | }
307 |
308 | // Close closes and cancels the query
309 | func (q *Query) Close(cancel bool) (err error) {
310 | if cancel {
311 | q.Context.Cancel()
312 | }
313 | if q.Result != nil {
314 | err = q.Result.Close()
315 | if err != nil {
316 | return g.Error(err, "could not close results")
317 | }
318 | }
319 | return
320 | }
321 |
322 | func (q *Query) ProcessResult() (err error) {
323 |
324 | proj := LoadProject(q.Project)
325 | if proj == nil {
326 | return g.Error("unable to load project %s", q.Project)
327 | }
328 |
329 | // delete query from map
330 | mux.Lock()
331 | delete(proj.Queries, q.ID)
332 |
333 | mux.Unlock()
334 |
335 | if q.Error != nil {
336 | return q.Error
337 | }
338 |
339 | if q.Affected == -1 && q.Stream != nil {
340 | q.Headers = q.Stream.Columns.Names()
341 | g.Debug("buffered %d rows", len(q.Stream.Buffer))
342 | }
343 |
344 | q.Close(false)
345 |
346 | q.End = time.Now().Unix()
347 |
348 | return
349 | }
350 |
--------------------------------------------------------------------------------
/state/roles.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | import (
4 | "strings"
5 |
6 | "github.com/slingdata-io/sling-cli/core/dbio/connection"
7 | )
8 |
9 | var (
10 | AllowAllRoleMap = RoleMap{
11 | "*": Role{
12 | "*": Grant{
13 | AllowRead: []string{"*"},
14 | AllowWrite: []string{"*"},
15 | AllowSQL: AllowSQLAny,
16 | },
17 | },
18 | }
19 | )
20 |
21 | // Role is a map of Grants per connection
22 | // each map key is a connection name
23 | // each map item is a grant entry for that connection
24 | type Role map[string]Grant
25 |
26 | // RoleMap is a map of roles
27 | // each map key is a role name
28 | // each map item is a Role entry for that role
29 | type RoleMap map[string]Role
30 |
31 | func (rm RoleMap) HasAccess(connection string) bool {
32 | for _, role := range rm {
33 | if _, ok := role[connection]; ok {
34 | return true
35 | } else if _, ok := role["*"]; ok {
36 | return true
37 | }
38 | }
39 | return false
40 | }
41 |
42 | func (rm RoleMap) GetPermissions(conn connection.Connection) (perms Permissions) {
43 | perms = Permissions{}
44 | for _, role := range rm {
45 | grant, ok := role[strings.ToLower(conn.Name)]
46 | if !ok {
47 | grant, ok = role["*"]
48 | }
49 |
50 | if ok {
51 | tables := grant.GetReadable(conn)
52 | for _, table := range tables {
53 | perms[table.FullName()] = PermissionRead
54 | }
55 |
56 | tables = grant.GetWritable(conn)
57 | for _, table := range tables {
58 | if p, ok := perms[table.FullName()]; ok {
59 | if p == PermissionRead {
60 | perms[table.FullName()] = PermissionReadWrite
61 | }
62 | } else {
63 | perms[table.FullName()] = PermissionWrite
64 | }
65 | }
66 | }
67 | }
68 |
69 | return
70 | }
71 |
72 | func (rm RoleMap) CanSQL(connection string) bool {
73 | for _, role := range rm {
74 | if ok := role.CanSQL(connection); ok {
75 | return ok
76 | }
77 | }
78 | return false
79 | }
80 |
81 | func (r Role) CanSQL(connection string) bool {
82 | if grant, ok := r[connection]; ok {
83 | return grant.AllowSQL == AllowSQLAny
84 | } else if grant, ok := r["*"]; ok {
85 | return grant.AllowSQL == AllowSQLAny
86 | }
87 | return false
88 | }
89 |
--------------------------------------------------------------------------------
/state/state.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | import (
4 | "sync"
5 | "time"
6 |
7 | "github.com/flarco/g"
8 | "github.com/slingdata-io/sling-cli/core/dbio/connection"
9 | )
10 |
11 | var (
12 | mux sync.Mutex
13 |
14 | // set a build time.
15 | RudderstackURL = ""
16 | )
17 |
18 | func init() {
19 | // routine loop
20 | go loop()
21 | }
22 |
23 | // Connection is a connection
24 | type Connection struct {
25 | Conn connection.Connection
26 | Source string
27 | Props map[string]string // to cache vars
28 | }
29 |
30 | // DefaultDB returns the default database
31 | func (c *Connection) DefaultDB() string {
32 | return c.Conn.Info().Database
33 | }
34 |
35 | // GetConnInstance gets the connection instance
36 | func CloseConnections() {
37 | mux.Lock()
38 | for _, p := range Projects {
39 | p.mux.Lock()
40 | for k, c := range p.Connections {
41 | g.LogError(c.Conn.Close())
42 | delete(p.Connections, k)
43 | }
44 | p.mux.Unlock()
45 | }
46 | mux.Unlock()
47 | }
48 |
49 | func ClearOldQueries() {
50 | mux.Lock()
51 | for _, p := range Projects {
52 | p.mux.Lock()
53 | for k, q := range p.Queries {
54 | if time.Since(q.lastTouch) > 10*time.Minute {
55 | delete(p.Queries, k)
56 | }
57 | }
58 | p.mux.Unlock()
59 | }
60 | mux.Unlock()
61 | }
62 |
63 | func loop() {
64 | ticker1Min := time.NewTicker(1 * time.Minute)
65 | defer ticker1Min.Stop()
66 | ticker10Min := time.NewTicker(10 * time.Minute)
67 | defer ticker10Min.Stop()
68 |
69 | for {
70 | select {
71 | case <-ticker1Min.C:
72 | case <-ticker10Min.C:
73 | go ClearOldQueries()
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/state/version.go:
--------------------------------------------------------------------------------
1 | package state
2 |
3 | // Version is the version number
4 | var Version = "dev"
5 |
--------------------------------------------------------------------------------