sql query usage
This commit is contained in:
parent
a718f74d24
commit
f4f293846b
2 changed files with 71 additions and 17 deletions
|
@ -1,5 +1,6 @@
|
|||
import { Request, Response } from "express";
|
||||
import DynamicQueryBuilder from "../../helpers/dynamicQueryBuilder";
|
||||
import { dataSource } from "../../data-source";
|
||||
|
||||
/**
|
||||
* @description get all table metas
|
||||
|
@ -37,22 +38,71 @@ export async function executeQuery(req: Request, res: Response): Promise<any> {
|
|||
let count = parseInt((req.query.count as string) ?? "25");
|
||||
const query = req.body.query;
|
||||
|
||||
try {
|
||||
let [rows, total] = await DynamicQueryBuilder.buildQuery(query, offset, count).getManyAndCount();
|
||||
if (typeof query == "string") {
|
||||
const upperQuery = query.trim().toUpperCase();
|
||||
if (!upperQuery.startsWith("SELECT") || /INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|TRUNCATE/.test(upperQuery)) {
|
||||
return res.json({
|
||||
stats: "error",
|
||||
sql: query,
|
||||
code: "UNALLOWED",
|
||||
msg: "Not allowed to change rows",
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
stats: "success",
|
||||
rows: rows,
|
||||
total: total,
|
||||
offset: offset,
|
||||
count: count,
|
||||
});
|
||||
} catch (error) {
|
||||
res.json({
|
||||
stats: "error",
|
||||
sql: error.sql,
|
||||
code: error.code,
|
||||
msg: error.sqlMessage,
|
||||
});
|
||||
try {
|
||||
let data: Array<any> = [];
|
||||
|
||||
const result = await dataSource
|
||||
.transaction(async (manager) => {
|
||||
data = await manager.query(query);
|
||||
|
||||
throw new Error("AllwaysRollbackQuery");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.message === "AllwaysRollbackQuery") {
|
||||
return {
|
||||
stats: "success",
|
||||
rows: data,
|
||||
total: data.length,
|
||||
offset: offset,
|
||||
count: count,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
stats: "error",
|
||||
sql: error.sql,
|
||||
code: error.code,
|
||||
msg: error.sqlMessage,
|
||||
};
|
||||
}
|
||||
});
|
||||
res.send(result);
|
||||
} catch (error) {
|
||||
res.json({
|
||||
stats: "error",
|
||||
sql: error.sql,
|
||||
code: error.code,
|
||||
msg: error.sqlMessage,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
let [rows, total] = await DynamicQueryBuilder.buildQuery(query, offset, count).getManyAndCount();
|
||||
|
||||
res.json({
|
||||
stats: "success",
|
||||
rows: rows,
|
||||
total: total,
|
||||
offset: offset,
|
||||
count: count,
|
||||
});
|
||||
} catch (error) {
|
||||
res.json({
|
||||
stats: "error",
|
||||
sql: error.sql,
|
||||
code: error.code,
|
||||
msg: error.sqlMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue