Implement db.project.delete().

Removes a project from the database, but only if the project is
empty, i.e., it has no preplots, no lines and no events in its
log (except deleted).
This commit is contained in:
D. Berge
2023-08-21 14:50:20 +02:00
parent ab5e3198aa
commit 8f8e8b7492

View File

@@ -0,0 +1,56 @@
const { setSurvey, pid2schema, pool } = require('../connection');
const event = require('../event');
const getSummary = require('./summary').get;
// Returns true if the project has no
// preplots, sequences or log entries,
// or if the project ID is not found
// in the database.
async function isDeletable (projectId) {
let summary;
try {
summary = await getSummary(projectId);
} catch (err) {
if (err.code == "42P01") {
// Project does not exist
return true;
} else {
throw err;
}
}
if (!summary) {
// projectId does not exist in the database
return true;
}
if (summary.total == 0 && summary.seq_raw == 0 && summary.seq_final == 0 && !summary.prod_duration) {
// Check for existing events (excluding deleted)
const events = await event.list(projectId, {limit: 1});
return events.length == 0;
}
return false;
};
async function del (projectId, opts = {}) {
if (await isDeletable(projectId)) {
const schema = await pid2schema(projectId);
if (schema) {
// NOTE: Should be reasonably safe as `schema` is not
// under user control.
const sql = `
DROP SCHEMA ${schema} CASCADE;
DELETE FROM public.projects WHERE schema = '${schema}';
`;
console.log(sql);
await pool.query(sql);
}
// We don't care if schema does not exist
} else {
throw { status: 405, message: "Project is not empty" }
}
}
module.exports = del;