Skip to content

Commit 273c7d5

Browse files
author
Snowflake107
committed
support DELETE
1 parent 66c5d0b commit 273c7d5

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/jsql/Database.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const handlers = {
66
insert: require('../util/methods/insert'),
77
drop: require('../util/methods/drop'),
88
update: require('../util/methods/update'),
9+
delete: require("../util/methods/delete"),
910
};
1011

1112
class Database {

src/util/methods/delete.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const { chunk } = require("../Util");
2+
3+
module.exports = (ast, db) => {
4+
if (ast.type.toLowerCase() !== 'delete') throw new TypeError('invalid query type');
5+
const table = ast.from[0].table;
6+
const data = db.db;
7+
if (!data[table]) throw new Error(`Table "${table}" does not exist`);
8+
9+
const point = { left: ast.where.left.value, op: ast.where.operator, right: ast.where.right.value };
10+
if (!data[table].keys.some(x => x.column === point.left)) throw new Error(`Column "${set.col}" does not exists in table "${table}"`);
11+
const bin = binOp(data[table], point);
12+
if (bin.index < 0) return;
13+
14+
bin.data.forEach(d => {
15+
data[table].data.splice(data[table].data.indexOf(d), 1);
16+
});
17+
18+
db.write(data);
19+
}
20+
21+
function binOp(data, clause) {
22+
switch (clause.op) {
23+
case "=":
24+
const child = chunk(data.data, 2);
25+
const fnx = m => m.key === clause.left && m.data === clause.right;
26+
const fn = x => x.find(fnx);
27+
28+
try {
29+
const data = child.find(fn);
30+
if (!data) throw new Error(`Could not verify operation "${clause.left} = ${clause.right}"`);
31+
return {
32+
data: data,
33+
index: child.findIndex(fn)
34+
};
35+
} catch {
36+
throw new Error(`Could not verify operation "${clause.left} = ${clause.right}"`);
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)