Notes/src/routes/api/sql.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-12-14 20:38:56 -05:00
"use strict";
import sql from "../../services/sql.js";
import becca from "../../becca/becca.js";
2024-04-06 23:12:22 +03:00
import { Request } from 'express';
import ValidationError from "../../errors/validation_error.js";
2017-12-14 20:38:56 -05:00
2020-06-20 12:31:38 +02:00
function getSchema() {
const tableNames = sql.getColumn(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`);
const tables = [];
for (const tableName of tableNames) {
tables.push({
name: tableName,
2020-06-20 12:31:38 +02:00
columns: sql.getRows(`PRAGMA table_info(${tableName})`)
});
}
return tables;
}
2024-04-06 23:12:22 +03:00
function execute(req: Request) {
const note = becca.getNoteOrThrow(req.params.noteId);
2024-04-06 23:12:22 +03:00
const content = note.getContent();
if (typeof content !== "string") {
throw new ValidationError("Invalid note type.");
}
const queries = content.split("\n---");
2017-12-14 20:38:56 -05:00
try {
const results = [];
for (let query of queries) {
query = query.trim();
2023-06-28 02:31:17 +08:00
while (query.startsWith('-- ')) {
2023-06-17 17:06:17 +10:00
// Query starts with one or more SQL comments, discard these before we execute.
2023-06-23 09:06:14 +10:00
const pivot = query.indexOf('\n');
query = pivot > 0 ? query.substr(pivot + 1).trim() : "";
}
if (!query) {
2019-12-09 21:31:38 +01:00
continue;
}
if (query.toLowerCase().startsWith('select') || query.toLowerCase().startsWith('with')) {
results.push(sql.getRows(query));
}
else {
results.push(sql.execute(query));
}
}
return {
success: true,
results
};
}
2024-04-06 23:12:22 +03:00
catch (e: any) {
return {
success: false,
error: e.message
};
}
}
2017-12-14 20:38:56 -05:00
export default {
getSchema,
execute
2020-06-20 12:31:38 +02:00
};