├── .gitignore ├── .idea └── workspace.xml ├── Dockerfile ├── LICENSE ├── README.md ├── config.example.hcl ├── go.mod ├── go.sum ├── init.go ├── js.go ├── macro.go ├── main.go ├── manager.go ├── routes.go ├── server_resp.go ├── server_rest.go ├── validate.go ├── vars.go └── website └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | .DS_Store -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | 15 | 16 | 17 | 18 | 19 | 24 | 25 | 26 | 28 | 29 | 31 | 32 | 33 | 34 | 37 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 1707753213390 63 | 68 | 69 | 70 | 71 | 73 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine 2 | 3 | RUN apk add --no-cache git gcc musl-dev 4 | 5 | RUN CGO_ENABLED=1 go get --tags "linux sqlite_stat4 sqlite_allow_uri_authority sqlite_fts5 sqlite_introspect sqlite_json" github.com/alash3al/sqler 6 | 7 | ENTRYPOINT ["sqler"] 8 | 9 | WORKDIR /root/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 [Mohamed Al Ashaal ] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SQLer 2 | ===== 3 | > `SQL-er` is a tiny portable server enables you to write APIs using SQL query to be executed when anyone hits it, also it enables you to define validation rules so you can validate the request body/query params, as well as data transformation using simple `javascript` syntax. `sqler` uses `nginx` style configuration language ([`HCL`](https://github.com/hashicorp/hcl)) and `javascript` engine for custom expressions. 4 | 5 | Table Of Contents 6 | ================= 7 | - [SQLer](#sqler) 8 | - [Table Of Contents](#table-of-contents) 9 | - [Features](#features) 10 | - [Quick Tour](#quick-tour) 11 | - [Supported DBMSs](#supported-dbmss) 12 | - [Docker](#docker) 13 | - [Configuration Overview](#configuration-overview) 14 | - [REST vs RESP](#rest-vs-resp) 15 | - [Sanitization](#sanitization) 16 | - [Validation](#validation) 17 | - [Authorization](#authorization) 18 | - [Data Transformation](#data-transformation) 19 | - [Aggregators](#aggregators) 20 | - [Issue/Suggestion/Contribution ?](#issuesuggestioncontribution) 21 | - [Author](#author) 22 | - [License](#license) 23 | 24 | Features 25 | ======== 26 | - Standalone with no dependencies. 27 | - Works with most of SQL databases out there including (`SQL Server`, `MYSQL`, `SQLITE`, `PostgreSQL`, `Cockroachdb`) 28 | - Built-in RESTful server 29 | - Built-in RESP `Redis Protocol`, you connect to `SQLer` using any `redis` client 30 | - Built-in `Javascript` interpreter to easily transform the result 31 | - Built-in Validators 32 | - Automatically uses prepared statements 33 | - Uses ([`HCL`](https://github.com/hashicorp/hcl)) configuration language 34 | - You can load multiple configuration files not just one, based on `unix glob` style pattern 35 | - Each `SQL` query could be named as `Macro` 36 | - Uses `Javascript` custom expressions. 37 | - Each macro has its own `Context` (`query params` + `body params`) as `.Input` which is `map[string]interface{}`, and `.Utils` which is a list of helper functions, currently it contains only `SQLEscape`. 38 | - You can define `authorizers`, an `authorizer` is just a simple webhook that enables `sqler` to verify whether the request should be done or not. 39 | - Trigger a `webhook` or another `macro` when a specific `macro` get executed. 40 | - Schedule specific macros to run at specific time using simple `cron` syntax. 41 | 42 | Quick Tour 43 | ========== 44 | - You install `sqler` using the right binary for your `os` from the [releases](https://github.com/alash3al/sqler/releases) page. 45 | - Let's say that you downloaded `sqler_darwin_amd64` 46 | - Let's rename it to `sqler`, and copy it to `/usr/local/bin` 47 | - Now just run `sqler -h`, you will the next 48 | ```bash 49 | ____ ___ _ 50 | / ___| / _ \| | ___ _ __ 51 | \___ \| | | | | / _ \ '__| 52 | ___) | |_| | |__| __/ | 53 | |____/ \__\_\_____\___|_| 54 | 55 | turn your SQL queries into safe valid RESTful apis. 56 | 57 | 58 | -config string 59 | the config file(s) that contains your endpoints configs, it accepts comma seprated list of glob style pattern (default "./config.example.hcl") 60 | -driver string 61 | the sql driver to be used (default "mysql") 62 | -dsn string 63 | the data source name for the selected engine (default "root:root@tcp(127.0.0.1)/test?multiStatements=true") 64 | -resp string 65 | the resp (redis protocol) server listen address (default ":3678") 66 | -rest string 67 | the http restful api listen address (default ":8025") 68 | -workers int 69 | the maximum workers count (default 4) 70 | ``` 71 | - you can specifiy multiple files for `-config` as [configuration](#configuration-overview), i.e `-config="/my/config/dir/*.hcl,/my/config/dir2/*.hcl"` 72 | - you need specify which driver you need and its `dsn` from the following: 73 | 74 | | Driver | DSN | 75 | ---------| ------ | 76 | | `mysql`| `usrname:password@tcp(server:port)/dbname?option1=value1&...`| 77 | | `postgres`| `postgresql://username:password@server:port/dbname?option1=value1`| 78 | | `sqlite3`| `/path/to/db.sqlite?option1=value1`| 79 | | `sqlserver` | `sqlserver://username:password@host/instance?param1=value¶m2=value` | 80 | | | `sqlserver://username:password@host:port?param1=value¶m2=value`| 81 | | | `sqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30`| 82 | | `mssql` | `server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`| 83 | | | `server=localhost;user id=sa;database=master;app name=MyAppName`| 84 | | | `odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName` | 85 | | | `odbc:server=localhost;user id=sa;database=master;app name=MyAppName` | 86 | | `hdb` (SAP HANA) | `hdb://user:password@host:port` | 87 | | `clickhouse` (Yandex ClickHouse) | `tcp://host1:9000?username=user&password=qwerty&database=clicks&read_timeout=10&write_timeout=20&alt_hosts=host2:9000,host3:9000` | 88 | 89 | Supported DBMSs 90 | =============== 91 | - `MYSQL`, `TiDB`, `MariaDB`, `Percona` and any MYSQL compatible server uses `mysql` driver. 92 | - `PostgreSQL`, `CockroachDB` and any PostgreSQL compatible server uses `postgres` driver. 93 | - `SQL Server`, `MSSQL`, `ADO`, `ODBC` uses `sqlserver` or `mssql` driver. 94 | - `SQLITE`, uses `sqlite3` driver. 95 | - `HANA` (SAP), uses `hdb` driver. 96 | - `Clickhouse`, uses `clickhouse` driver. 97 | 98 | Docker 99 | ====== 100 | > SQLer has a docker image called `alash3al/sqler` it is an automated build, you can use it like the following: 101 | 102 | ```bash 103 | 104 | # run the help message 105 | docker run --rm alash3al/sqler --help 106 | 107 | # connect to a local mysql 108 | docker run --network=host alash3al/sqler -driver=mysql -dsn=usr:pass@tcp(127.0.0.1:3306)/dbname 109 | 110 | # connect to another mysql container 111 | docker run -link mysql alash3al/sqler -driver=mysql -dsn=usr:pass@tcp(mysql:3306)/dbname 112 | 113 | ``` 114 | 115 | Configuration Overview 116 | ====================== 117 | ```hcl 118 | // create a macro/endpoint called "_boot", 119 | // this macro is private "used within other macros" 120 | // because it starts with "_". 121 | _boot { 122 | // the query we want to execute 123 | exec = < RESTful server could be used to interact directly with i.e `mobile, browser, ... etc`, in this mode `SQLer` is protected by `authorizers`, which gives you the ability to check authorization against another 3rd-party api. 201 | > Each macro you add to the configuration file(s) you can access to it by issuing a http request to `/`, every query param and json body will be passed to the macro `.Input`. 202 | 203 | > RESP server is just a basic `REDIS` compatible server, you connect to it using any `REDIS` client out there, even `redis-cli`, just open `redis-cli -p 3678 list` to list all available macros (`commands`), you can execute any macro as a redis command and pass the arguments as a json encoded data, i.e `redis-cli -p 3678 adduser "{\"user_name\": \"u6\", \"user_email\": \"email@tld.com\", \"user_password\":\"pass@123\"}"`. 204 | 205 | Sanitization 206 | ============= 207 | > `SQLer` uses prepared statements, you can bind inputs like the following: 208 | 209 | 210 | ```hcl 211 | addpost { 212 | // $input is a global variable holds all request inputs, 213 | // including the http headers too (prefixed with `http_`) 214 | // all http header keys are normalized to be in this form 215 | // `http_x_header_example`, `http_authorization` ... etc in lower case. 216 | bind { 217 | title = "$input.post_title" 218 | content = "$input.post_content" 219 | user_id = "$input.post_user" 220 | } 221 | 222 | exec = < Data validation is very easy in `SQLer`, it is all about simple `javascript` expression like this: 233 | 234 | ```hcl 235 | addpost { 236 | // if any rule returns false, 237 | // SQLer will return 422 code, with invalid rules. 238 | // 239 | // $input is a global variable holds all request inputs, 240 | // including the http headers too (prefixed with `http_`) 241 | // all http header keys are normalized to be in this form 242 | // `http_x_header_example`, `http_authorization` ... etc in lower case. 243 | validators { 244 | post_title_length = "$input.post_title && $input.post_title.trim().length > 0" 245 | post_content_length = "$input.post_content && $input.post_content.length > 0" 246 | post_user = "$input.post_user" 247 | } 248 | 249 | bind { 250 | title = "$input.post_title" 251 | content = "$input.post_content" 252 | user_id = "$input.post_user" 253 | } 254 | 255 | exec = < If you want to expose `SQLer` as a direct api to API consumers, you will need to add an authorization layer on top of it, let's see how to do that 265 | 266 | ```hcl 267 | addpost { 268 | authorizer = < using that trick, you can use any third-party Authentication service that will remove that hassle from your code. 290 | 291 | Data Transformation 292 | ==================== 293 | > In some cases we need to transform the resulted data into something more friendly to our API consumers, so I added `javascript` interpreter to `SQLer` so we can transform our data, each js code has a global variable called `$result`, it holds the result of the `exec` section, you should write your code like the following: 294 | 295 | ```hcl 296 | // list all databases, and run a transformer function 297 | databases { 298 | exec = "SHOW DATABASES" 299 | 300 | transformer = < `SQLer` helps you to merge multiple macros into one to minimize the API calls number, see the example bellow 319 | 320 | ```hcl 321 | databases { 322 | exec = "SHOW DATABASES" 323 | 324 | transformer = < I'm Mohamed Al Ashaal, just a problem solver :), you can view more projects from me [here](https://github.com/alash3al), and here is my email [m7medalash3al@gmail.com](mailto:m7medalash3al@gmail.com) 370 | 371 | License 372 | ======== 373 | > Copyright 2019 The SQLer Authors. All rights reserved. 374 | > Use of this source code is governed by a Apache 2.0 375 | > license that can be found in the [LICENSE](/License) file. 376 | 377 | -------------------------------------------------------------------------------- /config.example.hcl: -------------------------------------------------------------------------------- 1 | // create a macro/endpoint called "_boot", 2 | // this macro is private "used within other macros" 3 | // because it starts with "_". 4 | _boot { 5 | // the query we want to execute 6 | exec = < 0 { 30 | option = options[0] 31 | } 32 | 33 | if nil != option["method"] { 34 | method, _ = option["method"].(string) 35 | } 36 | 37 | if nil != option["headers"] { 38 | hdrs, _ := option["headers"].(map[string]interface{}) 39 | headers = make(map[string]string) 40 | for k, v := range hdrs { 41 | headers[k], _ = v.(string) 42 | } 43 | } 44 | 45 | if nil != option["body"] { 46 | body, _ = option["body"] 47 | } 48 | client := resty.New() 49 | resp, err := client.R().SetHeaders(headers).SetBody(body).Execute(method, url) 50 | if err != nil { 51 | return nil, err 52 | } 53 | 54 | rspHdrs := resp.Header() 55 | rspHdrsNormalized := map[string]string{} 56 | for k, v := range rspHdrs { 57 | rspHdrsNormalized[strings.ToLower(k)] = v[0] 58 | } 59 | 60 | return map[string]interface{}{ 61 | "status": resp.Status(), 62 | "statusCode": resp.StatusCode(), 63 | "headers": rspHdrsNormalized, 64 | "body": string(resp.Body()), 65 | }, nil 66 | } 67 | -------------------------------------------------------------------------------- /macro.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/alash3al/go-color" 9 | 10 | "github.com/go-resty/resty/v2" 11 | "github.com/jmoiron/sqlx" 12 | ) 13 | 14 | // Macro - a macro configuration 15 | type Macro struct { 16 | Methods []string 17 | Include []string 18 | Validators map[string]string 19 | Authorizer string 20 | Bind map[string]string 21 | Exec string 22 | Aggregate []string 23 | Transformer string 24 | 25 | Trigger struct { 26 | Webhook string 27 | Macro string 28 | } 29 | 30 | Cron string 31 | 32 | name string 33 | manager *Manager 34 | } 35 | 36 | // Call - executes the macro 37 | func (m *Macro) Call(input map[string]interface{}) (interface{}, error) { 38 | ok, err := m.authorize(input) 39 | if err != nil { 40 | return err.Error(), err 41 | } 42 | 43 | if !ok { 44 | return errAuthorizationError.Error(), errAuthorizationError 45 | } 46 | 47 | invalid, err := m.validate(input) 48 | if err != nil { 49 | return err.Error(), err 50 | } else if len(invalid) > 0 { 51 | return invalid, errValidationError 52 | } 53 | 54 | if err := m.runIncludes(input); err != nil { 55 | return err.Error(), err 56 | } 57 | 58 | var out interface{} 59 | 60 | if len(m.Aggregate) > 0 { 61 | out, err = m.aggregate(input) 62 | if err != nil { 63 | return err.Error(), err 64 | } 65 | } else { 66 | out, err = m.execSQLQuery(strings.Split(strings.TrimSpace(m.Exec), *flagSQLSeparator), input) 67 | if err != nil { 68 | return err.Error(), err 69 | } 70 | } 71 | 72 | out, err = m.transform(out) 73 | if err != nil { 74 | return err.Error(), err 75 | } 76 | 77 | go (func() { 78 | if m.Trigger.Webhook != "" { 79 | _, err := resty.New().R().SetDoNotParseResponse(true).SetHeader("Content-Type", "application/json").SetBody(map[string]interface{}{ 80 | "payload": out, 81 | }).Post(m.Trigger.Webhook) 82 | 83 | if err != nil { 84 | color.Red("[X]- " + err.Error()) 85 | } 86 | } 87 | 88 | if subm := m.manager.Get(m.Trigger.Macro); subm != nil { 89 | _, err := subm.Call(map[string]interface{}{ 90 | "payload": out, 91 | }) 92 | 93 | if err != nil { 94 | color.Red("[X]- " + err.Error()) 95 | } 96 | } 97 | })() 98 | 99 | return out, nil 100 | } 101 | 102 | // execSQLQuery - execute the specified sql query 103 | func (m *Macro) execSQLQuery(sqls []string, input map[string]interface{}) (interface{}, error) { 104 | args, err := m.buildBind(input) 105 | if err != nil { 106 | return nil, err 107 | } 108 | 109 | conn, err := sqlx.Open(*flagDBDriver, *flagDBDSN) 110 | if err != nil { 111 | return nil, err 112 | } 113 | defer conn.Close() 114 | 115 | for i, sql := range sqls { 116 | if strings.TrimSpace(sql) == "" { 117 | sqls = append(sqls[0:i], sqls[i+1:]...) 118 | } 119 | } 120 | 121 | for _, sql := range sqls[0 : len(sqls)-1] { 122 | sql = strings.TrimSpace(sql) 123 | if "" == sql { 124 | continue 125 | } 126 | if _, err := conn.NamedExec(sql, args); err != nil { 127 | return nil, err 128 | } 129 | } 130 | 131 | rows, err := conn.NamedQuery(sqls[len(sqls)-1], args) 132 | if err != nil { 133 | return nil, err 134 | } 135 | defer rows.Close() 136 | 137 | ret := []map[string]interface{}{} 138 | 139 | for rows.Next() { 140 | row, err := m.scanSQLRow(rows) 141 | if err != nil { 142 | continue 143 | } 144 | ret = append(ret, row) 145 | } 146 | 147 | return interface{}(ret), nil 148 | } 149 | 150 | // scanSQLRow - scan a row from the specified rows 151 | func (m *Macro) scanSQLRow(rows *sqlx.Rows) (map[string]interface{}, error) { 152 | row := make(map[string]interface{}) 153 | if err := rows.MapScan(row); err != nil { 154 | return nil, err 155 | } 156 | 157 | for k, v := range row { 158 | if nil == v { 159 | continue 160 | } 161 | 162 | switch v.(type) { 163 | case []uint8: 164 | v = []byte(v.([]uint8)) 165 | default: 166 | v, _ = json.Marshal(v) 167 | } 168 | 169 | var d interface{} 170 | if nil == json.Unmarshal(v.([]byte), &d) { 171 | row[k] = d 172 | } else { 173 | row[k] = string(v.([]byte)) 174 | } 175 | } 176 | 177 | return row, nil 178 | } 179 | 180 | // transform - run the transformer function 181 | func (m *Macro) transform(data interface{}) (interface{}, error) { 182 | transformer := strings.TrimSpace(m.Transformer) 183 | if transformer == "" { 184 | return data, nil 185 | } 186 | 187 | vm := initJSVM(map[string]interface{}{"$result": data}) 188 | 189 | v, err := vm.RunString(transformer) 190 | if err != nil { 191 | return nil, err 192 | } 193 | 194 | return v.Export(), nil 195 | } 196 | 197 | // authorize - run the authorizer function 198 | func (m *Macro) authorize(input map[string]interface{}) (bool, error) { 199 | authorizer := strings.TrimSpace(m.Authorizer) 200 | if authorizer == "" { 201 | return true, nil 202 | } 203 | 204 | var execError error 205 | 206 | vm := initJSVM(map[string]interface{}{"$input": input}) 207 | 208 | val, err := vm.RunString(m.Authorizer) 209 | if err != nil { 210 | return false, err 211 | } 212 | 213 | if execError != nil { 214 | return false, execError 215 | } 216 | 217 | return val.ToBoolean(), nil 218 | } 219 | 220 | // aggregate - run the aggregators 221 | func (m *Macro) aggregate(input map[string]interface{}) (map[string]interface{}, error) { 222 | ret := map[string]interface{}{} 223 | for _, k := range m.Aggregate { 224 | macro := m.manager.Get(k) 225 | if nil == macro { 226 | err := fmt.Errorf("unknown macro %s", k) 227 | return nil, err 228 | } 229 | out, err := macro.Call(input) 230 | if err != nil { 231 | return nil, err 232 | } 233 | ret[k] = out 234 | } 235 | return ret, nil 236 | } 237 | 238 | // validate - validate the input aginst the rules 239 | func (m *Macro) validate(input map[string]interface{}) (ret []string, err error) { 240 | if len(m.Validators) < 1 { 241 | return nil, nil 242 | } 243 | 244 | vm := initJSVM(map[string]interface{}{"$input": input}) 245 | 246 | for k, src := range m.Validators { 247 | val, err := vm.RunString(src) 248 | if err != nil { 249 | return nil, err 250 | } 251 | 252 | if !val.ToBoolean() { 253 | ret = append(ret, k) 254 | } 255 | } 256 | 257 | return ret, err 258 | } 259 | 260 | // buildBind - build the bind vars 261 | func (m *Macro) buildBind(input map[string]interface{}) (map[string]interface{}, error) { 262 | if len(m.Bind) < 1 { 263 | return nil, nil 264 | } 265 | 266 | vm := initJSVM(map[string]interface{}{"$input": input}) 267 | ret := map[string]interface{}{} 268 | 269 | for k, src := range m.Bind { 270 | val, err := vm.RunString(src) 271 | if err != nil { 272 | return nil, err 273 | } 274 | 275 | ret[k] = val.Export() 276 | } 277 | 278 | return ret, nil 279 | } 280 | 281 | // runIncludes - run the include function 282 | func (m *Macro) runIncludes(input map[string]interface{}) error { 283 | for _, name := range m.Include { 284 | macro := m.manager.Get(name) 285 | if nil == macro { 286 | return fmt.Errorf("macro %s not found", name) 287 | } 288 | _, err := macro.Call(input) 289 | if err != nil { 290 | return err 291 | } 292 | } 293 | return nil 294 | } 295 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The SQLer Authors. All rights reserved. 2 | // Use of this source code is governed by a Apache 2.0 3 | // license that can be found in the LICENSE file. 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "strconv" 9 | 10 | "github.com/alash3al/go-color" 11 | ) 12 | 13 | func main() { 14 | fmt.Println(color.MagentaString(sqlerBrand)) 15 | fmt.Printf("⇨ sqler server version: %s \n", color.GreenString(sqlerVersion)) 16 | fmt.Printf("⇨ sqler used driver is %s \n", color.GreenString(*flagDBDriver)) 17 | fmt.Printf("⇨ sqler used dsn is %s \n", color.GreenString(*flagDBDSN)) 18 | fmt.Printf("⇨ sqler workers count: %s \n", color.GreenString(strconv.Itoa(*flagWorkers))) 19 | fmt.Printf("⇨ sqler resp server available at: %s \n", color.GreenString(*flagRESPListenAddr)) 20 | fmt.Printf("⇨ sqler rest server available at: %s \n", color.GreenString(*flagRESTListenAddr)) 21 | 22 | err := make(chan error) 23 | 24 | go (func() { 25 | err <- initRESPServer() 26 | })() 27 | 28 | go (func() { 29 | err <- initRESTServer() 30 | })() 31 | 32 | if err := <-err; err != nil { 33 | color.Red(err.Error()) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /manager.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The SQLer Authors. All rights reserved. 2 | // Use of this source code is governed by a Apache 2.0 3 | // license that can be found in the LICENSE file. 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "io/ioutil" 9 | "os" 10 | "path/filepath" 11 | "strings" 12 | "sync" 13 | "text/template" 14 | 15 | "github.com/alash3al/go-color" 16 | "github.com/hashicorp/hcl" 17 | "github.com/robfig/cron/v3" 18 | ) 19 | 20 | // Manager - a macros manager 21 | type Manager struct { 22 | macros map[string]*Macro 23 | compiled *template.Template 24 | cron *cron.Cron 25 | sync.RWMutex 26 | } 27 | 28 | // NewManager - initialize a new manager 29 | func NewManager(configpath string) (*Manager, error) { 30 | manager := new(Manager) 31 | manager.macros = make(map[string]*Macro) 32 | manager.compiled = template.New("main") 33 | manager.cron = cron.New() 34 | 35 | for _, p := range strings.Split(configpath, ",") { 36 | files, _ := filepath.Glob(p) 37 | 38 | if len(files) < 1 { 39 | return nil, fmt.Errorf("invalid path (%s)", p) 40 | } 41 | 42 | for _, file := range files { 43 | data, err := ioutil.ReadFile(file) 44 | if err != nil { 45 | return nil, err 46 | } 47 | 48 | var config map[string]*Macro 49 | if err := hcl.Unmarshal(data, &config); err != nil { 50 | return nil, err 51 | } 52 | 53 | for k, v := range config { 54 | manager.macros[k] = v 55 | _, err := manager.compiled.New(k).Parse(v.Exec) 56 | if err != nil { 57 | return nil, err 58 | } 59 | v.manager = manager 60 | v.name = k 61 | v.Trigger.Webhook = strings.TrimSpace(v.Trigger.Webhook) 62 | v.Trigger.Macro = strings.TrimSpace(v.Trigger.Macro) 63 | 64 | if strings.TrimSpace(v.Cron) != "" { 65 | (func(v *Macro) { 66 | _, err := manager.cron.AddFunc(v.Cron, func() { 67 | fmt.Println(color.YellowString("=> Executing cron " + v.name)) 68 | if _, err := v.Call(map[string]interface{}{}); err != nil { 69 | fmt.Println(color.RedString("=> Faild executing cron " + v.name + " due to an error: " + err.Error())) 70 | } else { 71 | fmt.Println(color.GreenString("=> Executing cron " + v.name + " succeeded!")) 72 | } 73 | }) 74 | 75 | if err != nil { 76 | fmt.Println(color.RedString(err.Error())) 77 | os.Exit(1) 78 | } 79 | })(v) 80 | } 81 | } 82 | } 83 | } 84 | 85 | manager.cron.Start() 86 | 87 | return manager, nil 88 | } 89 | 90 | // Get - fetches the required macro 91 | func (m *Manager) Get(macro string) *Macro { 92 | m.RLock() 93 | defer m.RUnlock() 94 | 95 | return m.macros[macro] 96 | } 97 | 98 | // Size - return the size of the currently loaded configs 99 | func (m *Manager) Size() int { 100 | return len(m.macros) 101 | } 102 | 103 | // List - return a list of registered macros 104 | func (m *Manager) List() (ret []string) { 105 | for k := range m.macros { 106 | ret = append(ret, k) 107 | } 108 | 109 | return ret 110 | } 111 | -------------------------------------------------------------------------------- /routes.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The SQLer Authors. All rights reserved. 2 | // Use of this source code is governed by a Apache 2.0 3 | // license that can be found in the LICENSE file. 4 | package main 5 | 6 | import ( 7 | "strings" 8 | 9 | "github.com/labstack/echo" 10 | ) 11 | 12 | // routeIndex - the index route 13 | func routeIndex(c echo.Context) error { 14 | return c.JSON(200, map[string]interface{}{ 15 | "success": true, 16 | "message": "Welcome!", 17 | }) 18 | } 19 | 20 | // routeExecMacro - execute the requested macro 21 | func routeExecMacro(c echo.Context) error { 22 | macro := c.Get("macro").(*Macro) 23 | input := make(map[string]interface{}) 24 | body := make(map[string]interface{}) 25 | 26 | c.Bind(&body) 27 | 28 | for k := range c.QueryParams() { 29 | input[k] = c.QueryParam(k) 30 | } 31 | 32 | for k, v := range body { 33 | input[k] = v 34 | } 35 | 36 | headers := c.Request().Header 37 | for k, v := range headers { 38 | input["http_"+strings.Replace(strings.ToLower(k), "-", "_", -1)] = v[0] 39 | } 40 | 41 | out, err := macro.Call(input) 42 | if err != nil { 43 | code := errStatusCodeMap[err] 44 | if code < 1 { 45 | code = 500 46 | } 47 | return c.JSON(code, map[string]interface{}{ 48 | "success": false, 49 | "error": err.Error(), 50 | "data": out, 51 | }) 52 | } 53 | 54 | return c.JSON(200, map[string]interface{}{ 55 | "success": true, 56 | "data": out, 57 | }) 58 | } 59 | -------------------------------------------------------------------------------- /server_resp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/tidwall/redcon" 9 | ) 10 | 11 | func initRESPServer() error { 12 | return redcon.ListenAndServe( 13 | *flagRESPListenAddr, 14 | func(conn redcon.Conn, cmd redcon.Command) { 15 | // handles any panic 16 | defer (func() { 17 | if err := recover(); err != nil { 18 | conn.WriteError(fmt.Sprintf("fatal error: %s", (err.(error)).Error())) 19 | } 20 | })() 21 | 22 | // normalize the todo action "command" 23 | // normalize the command arguments 24 | todo := strings.TrimSpace(string(cmd.Args[0])) 25 | todoNormalized := strings.ToLower(todo) 26 | args := []string{} 27 | for _, v := range cmd.Args[1:] { 28 | v := strings.TrimSpace(string(v)) 29 | args = append(args, v) 30 | } 31 | 32 | // internal command to pick a database 33 | if todoNormalized == "select" { 34 | conn.WriteString("OK") 35 | return 36 | } 37 | 38 | // internal ping-pong 39 | if todoNormalized == "ping" { 40 | conn.WriteString("PONG") 41 | return 42 | } 43 | 44 | // ECHO 45 | if todoNormalized == "echo" { 46 | conn.WriteString(strings.Join(args, " ")) 47 | return 48 | } 49 | 50 | // HELP|INFO|LIST 51 | if todoNormalized == "list" || todoNormalized == "help" || todoNormalized == "info" { 52 | conn.WriteArray(macrosManager.Size()) 53 | for _, v := range macrosManager.List() { 54 | conn.WriteBulkString(v) 55 | } 56 | return 57 | } 58 | 59 | // close the connection 60 | if todoNormalized == "quit" { 61 | conn.WriteString("OK") 62 | conn.Close() 63 | return 64 | } 65 | 66 | macro := macrosManager.Get(todo) 67 | if nil == macro { 68 | conn.WriteError("not found") 69 | conn.Close() 70 | return 71 | } 72 | 73 | var input map[string]interface{} 74 | if len(args) > 0 { 75 | json.Unmarshal([]byte(args[0]), &input) 76 | } 77 | 78 | // handle our command 79 | commandExecMacro(conn, macro, input) 80 | }, 81 | func(conn redcon.Conn) bool { 82 | conn.SetContext(map[string]interface{}{}) 83 | return true 84 | }, 85 | nil, 86 | ) 87 | } 88 | 89 | // commandExecMacro - resp command handler 90 | func commandExecMacro(conn redcon.Conn, macro *Macro, input map[string]interface{}) { 91 | out, err := macro.Call(input) 92 | if err != nil { 93 | conn.WriteArray(2) 94 | conn.WriteInt(0) 95 | 96 | j, _ := json.Marshal(err.Error()) 97 | 98 | conn.WriteBulk(j) 99 | 100 | return 101 | } 102 | 103 | jsonOUT, _ := json.Marshal(out) 104 | 105 | conn.WriteArray(2) 106 | conn.WriteInt(1) 107 | conn.WriteBulk(jsonOUT) 108 | } 109 | -------------------------------------------------------------------------------- /server_rest.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The SQLer Authors. All rights reserved. 2 | // Use of this source code is governed by a Apache 2.0 3 | // license that can be found in the LICENSE file. 4 | package main 5 | 6 | import ( 7 | "strings" 8 | 9 | "github.com/labstack/echo" 10 | "github.com/labstack/echo/middleware" 11 | ) 12 | 13 | // initialize RESTful server 14 | func initRESTServer() error { 15 | e := echo.New() 16 | e.HideBanner = true 17 | e.HidePort = true 18 | 19 | e.Pre(middleware.RemoveTrailingSlash()) 20 | e.Use(middleware.CORS()) 21 | e.Use(middleware.GzipWithConfig(middleware.GzipConfig{Level: 9})) 22 | e.Use(middleware.Recover()) 23 | 24 | e.GET("/", routeIndex) 25 | e.Any("/:macro", routeExecMacro, middlewareAuthorize) 26 | 27 | return e.Start(*flagRESTListenAddr) 28 | } 29 | 30 | // middlewareAuthorize - the authorizer middleware 31 | func middlewareAuthorize(next echo.HandlerFunc) echo.HandlerFunc { 32 | return func(c echo.Context) error { 33 | if strings.HasPrefix(c.Param("macro"), "_") { 34 | return c.JSON(403, map[string]interface{}{ 35 | "success": false, 36 | "error": "access not allowed", 37 | }) 38 | } 39 | 40 | macro := macrosManager.Get(c.Param("macro")) 41 | if macro == nil { 42 | return c.JSON(404, map[string]interface{}{ 43 | "success": false, 44 | "error": "resource not found", 45 | }) 46 | } 47 | 48 | if len(macro.Methods) < 1 { 49 | macro.Methods = []string{c.Request().Method} 50 | } 51 | 52 | methodIsAllowed := false 53 | for _, method := range macro.Methods { 54 | method = strings.ToUpper(method) 55 | if c.Request().Method == method { 56 | methodIsAllowed = true 57 | break 58 | } 59 | } 60 | 61 | if !methodIsAllowed { 62 | return c.JSON(405, map[string]interface{}{ 63 | "success": false, 64 | "error": "method not allowed", 65 | }) 66 | } 67 | 68 | c.Set("macro", macro) 69 | 70 | return next(c) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /validate.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The SQLer Authors. All rights reserved. 2 | // Use of this source code is governed by a Apache 2.0 3 | // license that can be found in the LICENSE file. 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "strings" 9 | 10 | "github.com/asaskevich/govalidator" 11 | ) 12 | 13 | // Validate - validates the specified data against the specified validators 14 | func Validate(data map[string]interface{}, validators map[string][]string) map[string][]string { 15 | invalid, result := 0, map[string][]string{} 16 | for k, rules := range validators { 17 | result[k] = []string{} 18 | value, exists := data[k] 19 | valuestr := strings.TrimSpace(fmt.Sprintf("%v", value)) 20 | for _, r := range rules { 21 | if r == "required" && !exists || valuestr == "" { 22 | invalid++ 23 | result[k] = append(result[k], "required") 24 | } else if ruler, ok := govalidator.TagMap[r]; ok && !ruler(valuestr) { 25 | invalid++ 26 | result[k] = append(result[k], r) 27 | } else { 28 | parts := strings.SplitN(r, ":", 2) 29 | if len(parts) < 2 { 30 | parts = append(parts, "") 31 | } 32 | r, args := parts[0], parts[1] 33 | args = strings.TrimSpace(args) 34 | if ruler, ok := govalidator.ParamTagMap[r]; ok { 35 | if !ruler(valuestr, strings.Split(args, ",")...) { 36 | invalid++ 37 | result[k] = append(result[k], r) 38 | } 39 | } 40 | } 41 | } 42 | 43 | if len(result[k]) < 1 { 44 | delete(result, k) 45 | } 46 | } 47 | return result 48 | } 49 | -------------------------------------------------------------------------------- /vars.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The SQLer Authors. All rights reserved. 2 | // Use of this source code is governed by a Apache 2.0 3 | // license that can be found in the LICENSE file. 4 | package main 5 | 6 | import ( 7 | "errors" 8 | "flag" 9 | "runtime" 10 | ) 11 | 12 | var ( 13 | flagDBDriver = flag.String("driver", "mysql", "the sql driver to be used") 14 | flagDBDSN = flag.String("dsn", "root:root@tcp(127.0.0.1)/test?multiStatements=true", "the data source name for the selected engine") 15 | flagAPIFile = flag.String("config", "./config.example.hcl", "the config file(s) that contains your endpoints configs, it accepts comma seprated list of glob style pattern") 16 | flagRESTListenAddr = flag.String("rest", ":8025", "the http restful api listen address") 17 | flagRESPListenAddr = flag.String("resp", ":3678", "the resp (redis protocol) server listen address") 18 | flagWorkers = flag.Int("workers", runtime.NumCPU(), "the maximum workers count") 19 | flagSQLSeparator = flag.String("sep", `---\\--`, "multi sql query separator") 20 | ) 21 | 22 | var ( 23 | errNoMacroFound = errors.New("Resource not found") 24 | errValidationError = errors.New("Validation error") 25 | errAuthorizationError = errors.New("Authorization Error") 26 | ) 27 | 28 | var ( 29 | errStatusCodeMap = map[error]int{ 30 | errNoMacroFound: 404, 31 | errValidationError: 422, 32 | errAuthorizationError: 401, 33 | } 34 | ) 35 | 36 | var ( 37 | macrosManager *Manager 38 | ) 39 | 40 | const ( 41 | sqlerVersion = "v2.1" 42 | sqlerBrand = ` 43 | 44 | ____ ___ _ 45 | / ___| / _ \| | ___ _ __ 46 | \___ \| | | | | / _ \ '__| 47 | ___) | |_| | |__| __/ | 48 | |____/ \__\_\_____\___|_| 49 | 50 | turn your SQL queries into safe valid RESTful apis. 51 | 52 | ` 53 | ) 54 | -------------------------------------------------------------------------------- /website/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | SQLer - unleash the power of SQL 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 |

SQLer

17 |
18 |
19 |
20 |
There is full revamp in progress, stay tuned 🤗
21 |
22 |
23 |
star us on github
24 |
25 | 26 | 27 | --------------------------------------------------------------------------------