Skip to content

Commit c144033

Browse files
enhanced application to accept parameterized sqlite queries via HTTP POST + application/json. uppdated readme.md
1 parent bef98f1 commit c144033

3 files changed

Lines changed: 944 additions & 2 deletions

File tree

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,13 @@ $ fg
107107
^C
108108
```
109109

110+
## Parameterized Queries (must use HTTP POST with content-type=application/json. 'params' element must be an array in request body)
111+
```console
112+
$ sqliteproxy --db currenttime.sqlite
113+
$ curl -i -X POST -H "Content-Type: application/json" -d "{\"sql\":\"select DATETIME(?) AS UTC_ISO\",\"params\":[\"now\"]}" http://localhost:2048
114+
$ [{"UTC_ISO":"2020-09-10 02:06:02"}]
115+
```
116+
110117
## CORS
111118

112119
```console

main.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,27 @@ if (flags.get("cors").length > 0) {
4646
function getSqlExecutor(httpRequestFieldName) {
4747
return function (req, res) {
4848
const sql = req[httpRequestFieldName].sql;
49+
let params = [];
50+
if (httpRequestFieldName === "body" && req.is('application/json'))
51+
{
52+
params = req[httpRequestFieldName].params;
53+
if (params == undefined || params == null)
54+
{
55+
params = [];
56+
}
57+
}
4958
if (!sql) {
5059
return res.send([]);
5160
}
5261

5362
let db;
5463
try {
64+
if (!Array.isArray(params))
65+
{
66+
var err = new Error("'params' element in http request body must be an array!");
67+
err["code"] = 10000;
68+
throw err;
69+
}
5570
const readonly = flags.get("readonly");
5671
db = new Database(flags.get("db"), { readonly });
5772
if (!readonly) {
@@ -67,9 +82,11 @@ function getSqlExecutor(httpRequestFieldName) {
6782
let rows = [];
6883
try {
6984
if (sql.toLowerCase().includes("select")) {
70-
rows = db.prepare(sql).all();
85+
var stmt = db.prepare(sql);
86+
rows = stmt.all(params);
7187
} else {
72-
db.prepare(sql).run();
88+
var stmt = db.prepare(sql);
89+
stmt.run(params);
7390
}
7491
} catch (err) {
7592
res.status(400);

0 commit comments

Comments
 (0)