A REST-like API to query a SQL database through HTTP
7.0K
sqlrest is an API proxy for MS-SQL databases for easier database access in serverless functions
The idea came from the need want to turn full size APIs into a group of serverless functions. It was quickly discovered that the connections to a database take around 5-7 seconds. No good for a serverless function!
The thought is to create an ultra-minimalist API that acts as a proxy in front of a database in order to maintain the connection, as well as handle the pooling while the functions can focus on being functional.
The function would build the required SQL statment to be executed, and send it to SqlRest for execution on the remote DB. SqlRest does nothing more than passing the query (or procedure name) to the connected database server for execution. The response will depend on the route/command. Select/Query would return a json array of column names and row results Example Results:
data: {
[
[
"Column1",
"Column2"
],
[
"Result1_1",
"Result1_2"
],
[
"Result2_1",
"Result2_2"
]
]
}
Errors will be returned with an appropriate HTTP response code and a "message" property containing the reason of the error
Example Error Result:
{
"message": "Query must contain at least 1 'SELECT' statement for 'Query' operation"
}
Also, errors encountered in the database will include an "error" property with the error being passed directly from the database Example DB Error Response:
{
"error": {
"Number": 102,
"State": 1,
"Class": 15,
"Message": "Incorrect syntax near 'Blah:'.",
"ServerName": "efe87d4ca854",
"ProcName": "",
"LineNo": 1
},
"message": "Error returned from database"
}
Pull the image from Docker Hub:
docker pull burtonr/sqlrest:0.2
| Name | Value |
|---|---|
| DATABASE_USERNAME | The username to log in to the SQL Server with |
| DATABASE_PASSWORD | The password associated with the user |
| DATABASE_SERVER | The IP address, or hostname, of the SQL server. Do not include the instance, or port number, we got that covered for you (assuming 1433 (default)) :) |
| SQLREST_ALLOWED_REALMS | A comma separated list of strings to designate what service is permitted to access this instance of sqlrest |
| SQLREST_API_KEY | The shared secret key used to hash the request |
Run the image with the following command (replacing the environment variables with your own)
docker run -d -p 5050:5050 -e DATABASE_USERNAME=sa -e DATABASE_PASSWORD=secretSauce2! -e DATABASE_SERVER=172.17.0.2 -e SQLREST_ALLOWED_REALMS=test-func,qa-func -e SQLREST_API_KEY=sqlrestTestKey --name sqlrest burtonr/sqlrest:0.2
| Name | Value | Default |
|---|---|---|
| DATABASE_NAME | The name of the database to connect to | blank (i.e. master) |
The API exposes the following endpoints:
/connectv1/procedurev1/queryv1/insertv1/deletev1/update(the v1 is an example of the API version that will update as breaking changes happen)
Each request must include an Authorization header
The value of this header includes 4 parts separated by a colon ( : )
SQLREST_ALLOWED_REALMS environment variableExample:
Authorization: testing-func:fb1ded9f15a6d8134b3db1640c21cff2b0b22860a1720c54e7fd4938ba46b7f2:bbd37ca7-f270-45ee-9e5c-fa4a5de59a30:1520527620822
Sending a GET request to this endpoint forces the API to attempt to reconnect to the database using the environment variables provided.
There is a process that runs every 2 minutes to ping the database that will reconnect if it fails. Use this endpoint if you don't want to wait for that process to run
If it is already connected, it will return with a success, otherwise it will attempt the connection and return either a 200 or 500
Note: For this
GETrequest, thesignaturesection of theAuthorizationheader is not evaluated and may be left blank
Send a POST request to this endpoint to execute a SQL stored procedure and optionally get the results back
name property.
DATABASE_NAME env var. By default, this will run against the master databaseparameters object that includes the parameter name and valueexecuteOnly that, when false, returns the result set from the stored procedureA full request (to execute with parameters and return the results) would look like this:
{
"name": "sales.dbo.sp_get_customers",
"parameters": {
"title": "scuba",
"firstName": "Steve",
},
"executeOnly": false
}
The executeOnly property defaults to true so that procedures will not return values unless explicitly requested
This endpoint builds the SQL command to be executed as a string.
The above example will generate the following string to be sent to the SQL server:
EXEC sales.dbo.sp_get_customers @title = "scuba", @firstName = "Steve"
Send a POST request to this endpoint to execute a SQL query and get the results back
There are some basic syntax checks.
query in the request bodySELECT commandThe query passed in is sent to the database directly with no modifications.
Note: SQL connects to the master database by default, so be sure to include a USE statement
USE Database_Name; SELECT 1 FROM Table_Name
or use the full object name in the table definition
SELECT 1 FROM [Database_Name].[dbo].[Table_Name]
You could also set the environment variable DATABASE_NAME to set a default database name. Note, that if the default schema is not dbo, you will need to include that in the query as well even with the database name being set.
See above for examples of error and success responses
Send a PUT request to this endpoint to execure a SQL insert
There are some basic syntax checks.
insert in the request bodyINSERT INTO commandThe function that handles executing inserts will first create a transaction, then execute the command. If there is an error, or something goes wrong (panic), the transaction will roll back.
The request and command passed in follow the same rules as the Query endpoint. Be sure to include the database name
No results are returned with this command. To get the inserted values, you will need to Query for them.
Not yet implemented
Send a POST request to this endpoint to execute a SQL update
There are some basic syntax checks.
update in the request bodyUPDATE commandWHERE clause
The function that handles executing updates will first create a transaction, then execute the command. If there is an error, or something goes wrong (panic), the transaction will roll back.
The request and command passed in follow the same rules as the Query endpoint. Be sure to include the database name
No results are returned with this command. To get the updated values, you will need to Query.
sqlrest uses HMAC authorization to validate the requests being sent. The Authorization header is used to send the validation criteria to sqlrest (see Headers)
The validation uses the following environment variables:
SQLREST_ALLOWED_REALMS
SQLREST_API_KEY
This (mostly) follows the familiar REST practices as well as special handling of requests based on the route.
localhost:8080/v1/queryfunc will have the version appended to itqueryHandler.go -> queryHandler.v1.goExecuteQuery() -> ExecuteQueryV1()Update and Insert calls return the modified/created entry?
Content type
Image
Digest
Size
10.6 MB
Last updated
about 7 years ago
docker pull burtonr/sqlrest:0.3