-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.js
More file actions
90 lines (84 loc) · 2.32 KB
/
Copy pathtable.js
File metadata and controls
90 lines (84 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
module.exports = class Table {
constructor(thread, name, properties) {
this.name = name;
this.thread = thread;
this.properties = properties;
for (const i in properties) {
if (properties[i].column_key === 'PRI') {
this.primaryKey = properties[i].column_name;
break;
}
}
}
async grep(data) {
if (!Array.isArray(data)) data = [data];
const inserts = [], updates = [];
data.forEach(item => {
if (item[this.primaryKey]) {
const pk = item[this.primaryKey];
delete item[this.primaryKey];
updates.push([
item,
`??=?`,
this.primaryKey,
pk
]);
} else {
inserts.push(item);
}
});
if (inserts.length) {
await this.insert(inserts);
}
if (updates.length) {
for (let i = 0; i < updates.length; i++) {
await this.update(...updates[i]);
}
}
}
async insert(data) {
let one = false;
if (!Array.isArray(data)) {
data = [data];
one = true;
}
const result = await Promise.all(data.map(res => this.thread.exec('INSERT INTO ?? SET ?', this.name, res)));
if (one) return result[0];
return result;
}
async update(value, where, ...wheres) {
let fields = [], values = [this.name];
for (const key in value){
fields.push('`' + key + '`=?');
values.push(value[key]);
}
let sql = `UPDATE ?? SET ${fields.join(',')}`;
if ( where ){
sql += ' WHERE ' + where;
values = values.concat(wheres);
}
return (await this.thread.exec(sql, ...values)).changedRows;
}
async delete(where, ...wheres){
let sql = `DELETE FROM ??`, values = [this.name];
if ( where ){
sql += ' WHERE ' + where;
values = values.concat(wheres);
}
return (await this.thread.exec(sql, ...values)).affectedRows;
}
async remove(...values) {
await Promise.all(values.map(value => this.delete('??=?', this.primaryKey, value)));
}
async exec(columns, where, ...wheres) {
const isall = columns==='*' || !columns;
let sql = `SELECT ${isall ? '*' : '??' } FROM ??`, values = [];
if (!isall) values.push(columns);
values.push(this.name);
if ( where ){
sql += ' WHERE ' + where;
values = values.concat(wheres);
}
return await this.thread.exec(sql, ...values);
}
}