sql query usage

This commit is contained in:
Julian Krauser 2024-12-17 16:52:15 +01:00
parent a718f74d24
commit f4f293846b
2 changed files with 71 additions and 17 deletions

View file

@ -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,6 +38,54 @@ export async function executeQuery(req: Request, res: Response): Promise<any> {
let count = parseInt((req.query.count as string) ?? "25");
const query = req.body.query;
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",
});
}
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();
@ -56,3 +105,4 @@ export async function executeQuery(req: Request, res: Response): Promise<any> {
});
}
}
}

View file

@ -79,7 +79,7 @@ export default abstract class DynamicQueryBuilder {
}
for (const select of selects) {
if (firstSelect) {
if (firstSelect && depth == 0) {
query.select(`${alias}.${select}`);
firstSelect = false;
} else {
@ -214,6 +214,10 @@ export default abstract class DynamicQueryBuilder {
query += ` LIKE :${parameterKey}`;
parameters[parameterKey] = `%${condition.value}`;
break;
case "timespanEq":
query += ` BETWEEN :${parameterKey}_start AND :${parameterKey}_end`;
parameters[`${parameterKey}_start`] = new Date(new Date().getFullYear() - (condition.value as number), 0, 1);
parameters[`${parameterKey}_end`] = new Date(new Date().getFullYear() - (condition.value as number), 11, 31);
}
return { query, parameters };