-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb_action.js
368 lines (323 loc) · 9.89 KB
/
db_action.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
const {mysql_obj,promise_mysql_pool,search_key_in_deep_obj:skido} = require('./mysql_pool_class.js');
let lastest_time_stamp;
//=========================================================
function handle_error(error)
{
console.log(error);
}
function getType(things)
{
let result = typeof things;
switch(result)
{
case "object":
if (Array.isArray(things)) return 'array';
return 'json';
default:
return result;
}
}
function filterOf_str_json(content)
{
let string_filter = /\`|\"|\\|\'|\;|\//g;
let result = content;
try {
switch(getType(content))
{
case "json":
result={};
for(let x in content) result[filterOf_str_json(x)]=filterOf_str_json(content[x]);
break;
case "array":
result=[];
for(let x of content) result.push(filterOf_str_json(x));
break;
case "string":
result = content.replace(string_filter,"");
break;
}
return result;
} catch (error) {
console.log("error in string json filter ",error);
return "";
}
}
async function read_record_result_process(error,result,field,callback){
if(error)
{
handle_error(error);
callback(error,result,field);
return;
}
result = result.map(el=>{
//save
// console.log(el,Date.parse(el.timestamp),el.timestamp)
el['json_data']['dbId']=el['index'];
return el['json_data'];
});
callback(error,result,field);
}
async function add_record(data,callback)
{
//
//clean the data for sql injection
data = filterOf_str_json(data);
let stepPreparingData ={
user: data.username,
action : data['action']||undefined,
content : JSON.stringify(data.data),
}
let steps_feedback = await promise_mysql_pool.insert([stepPreparingData],"cantonese_dictionary_steps_data");
let recordIndex = data['data']["dbId"];
delete data['data']["dbId"];
let masterPreparingData = {
english:data.data['english'],
chinese:data.data['chinese'],
tags:JSON.stringify(data.data['tags']),
json_data:JSON.stringify(data.data),
};
let master_feedback = null;
if(typeof recordIndex!=="number")
{
//insert
master_feedback = await promise_mysql_pool.insert([masterPreparingData],"cantonese_dictionary_master_data");
}
else
{
//update
master_feedback = await promise_mysql_pool.update(masterPreparingData,"cantonese_dictionary_master_data",`\`index\`="${recordIndex}"`);
master_feedback['insertId']=recordIndex;
}
/* example of master feedback
[
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 15,
info: '',
serverStatus: 2,
warningStatus: 0
},
undefined
]
*/
let rst = {
steps_affectedRows:skido(steps_feedback,"affectedRows"),
master_affectedRows:skido(master_feedback,"affectedRows"),
master_insertId:skido(master_feedback,"insertId"),
}
callback(rst);
}
async function read_user_keypair(name)
{
const [rows,fields] = await promise_mysql_pool.query(`SELECT value FROM \`cantonese_dictionary_config\` where \`key\`="input_keypair" and JSON_EXTRACT(value, "$.${name}"); `);
return rows[0]['value'];
}
async function read_lastest_record(cb){
//
let sql = `select * from \`cantonese_dictionary_master_data\` where \`deleted\`=0 order by \`timestamp\` desc limit 50; `;
mysql_obj.get_all(sql,(error,result,field)=>{
read_record_result_process(error,result,field,cb)}
);
}
async function read_record(search_obj,cb)
{
//keyword not empty======================================
let k_where = "";
if(search_obj['keyword'])
{
let [chn_where,eng_where] = [[],[]];
let chn_regex = /[\u4e00-\u9fa5]/;
for(let x of search_obj['keyword']){
if(chn_regex.test(x))
{//chn
chn_where.push(`"${x}"`);
}
else
{//eng
eng_where.push(`"${x}"`);
}
}
if(chn_where.length>0) k_where+=` \`chinese\` IN (${chn_where.join(",")})`;
if(eng_where.length>0) k_where+=` ${chn_where.length>0?" OR ":""} \`english\` IN (${eng_where.join(",")})`;
if(k_where!=="") k_where=" and ("+ k_where + ")";
}
//keyword not empty======================================
//tags not empty========================================
///select * from `cantonese_dictionary_master_data` where `deleted`=0 and JSON_SEARCH(`tags`,'one','test');
let t_where = "";
if(search_obj['tags']){
let tags_arr = [];
search_obj['tags'].forEach(el=>{
tags_arr.push(`JSON_SEARCH(\`tags\`,'one','${el}')`);
})
if(tags_arr.length>0) t_where=` (${tags_arr.join(" or ")})`;
}
//tags not empty==========================================
//all empty==========================================
let empty_where ="";
if(k_where===""&&t_where===""){
empty_where =" LIMIT 50";
}
//all empty==========================================
if(t_where!=="")t_where=(k_where===""?"and ":"or ")+t_where;
let sql = `select * from \`cantonese_dictionary_master_data\` where \`deleted\`=0 ${k_where} ${t_where} ${empty_where}`;
//example select * from `cantonese_dictionary_master_data` where `deleted`=0 and ( `chinese` IN ("通知","继续") OR `english` IN ("country","virus"))
mysql_obj.get_all(sql,(error,result,field)=>{
read_record_result_process(error,result,field,cb)}
);
}
async function delete_record(data,cb)
{
//
/* data example
{
username: 'hector',
data: {
dbId: 35,
english: '111h222',
chinese: '333344',
phonics: '5354',
'chinese sentence example': 'llll',
'english sentence example': '',
tags: { test: 'test', hector: 'hector' }
},
action: 'addrecord',
random: 0.09290560557099958
}
*/
try {
let stepPreparingData ={
user: data.username,
action : data.action,
content : JSON.stringify(data.data),
}
let steps_feedback = await promise_mysql_pool.insert([stepPreparingData],"cantonese_dictionary_steps_data");
let recordIndex = data['data']["dbId"];
delete data['data']["dbId"];
let masterPreparingData = {
deleted:1,
};
let master_feedback = await promise_mysql_pool.update(masterPreparingData,"cantonese_dictionary_master_data",`\`index\`="${recordIndex}"`);
/* master_feedback example
[
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
info: 'Rows matched: 1 Changed: 1 Warnings: 0',
serverStatus: 2,
warningStatus: 0,
changedRows: 1
},
undefined
]
*/
let rst = {
steps_affectedRows:skido(steps_feedback,"affectedRows"),
master_affectedRows:skido(master_feedback,"affectedRows"),
master_insertId:recordIndex,
}
cb(rst);
} catch (error) {
cb({"error":error.toString()});
}
}
///////////////////////////////////////////////////////////////
module.exports = {
add_record,
read_record,
read_lastest_record,
delete_record,
handle_error,
read_user_keypair,
};
///mysql table stucture below
/*
-- phpMyAdmin SQL Dump
-- version 5.2.0
-- https://www.phpmyadmin.net/
--
-- Host: :3306
-- Generation Time: Sep 24, 2022 at 01:04 PM
-- Server version: 8.0.30-0ubuntu0.22.04.1
-- PHP Version: 8.1.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Database: `cantoese_dictionary`
--
-- --------------------------------------------------------
--
-- Table structure for table `cantonese_dictionary_config`
--
CREATE TABLE `cantonese_dictionary_config` (
`index` int NOT NULL,
`key` varchar(20) NOT NULL,
`value` json NOT NULL,
`timestamp` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-- --------------------------------------------------------
--
-- Table structure for table `cantonese_dictionary_master_data`
--
CREATE TABLE `cantonese_dictionary_master_data` (
`index` int NOT NULL,
`english` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`chinese` varchar(200) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`json_data` json NOT NULL,
`tags` json NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted` int NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-- --------------------------------------------------------
--
-- Table structure for table `cantonese_dictionary_steps_data`
--
CREATE TABLE `cantonese_dictionary_steps_data` (
`index` int NOT NULL,
`user` varchar(50) NOT NULL,
`action` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`content` json NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `cantonese_dictionary_config`
--
ALTER TABLE `cantonese_dictionary_config`
ADD PRIMARY KEY (`index`);
--
-- Indexes for table `cantonese_dictionary_master_data`
--
ALTER TABLE `cantonese_dictionary_master_data`
ADD PRIMARY KEY (`index`),
ADD KEY `timestamp` (`timestamp`);
--
-- Indexes for table `cantonese_dictionary_steps_data`
--
ALTER TABLE `cantonese_dictionary_steps_data`
ADD PRIMARY KEY (`index`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `cantonese_dictionary_config`
--
ALTER TABLE `cantonese_dictionary_config`
MODIFY `index` int NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `cantonese_dictionary_master_data`
--
ALTER TABLE `cantonese_dictionary_master_data`
MODIFY `index` int NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `cantonese_dictionary_steps_data`
--
ALTER TABLE `cantonese_dictionary_steps_data`
MODIFY `index` int NOT NULL AUTO_INCREMENT;
COMMIT;
*/