-
Notifications
You must be signed in to change notification settings - Fork 1
/
mysql.js
86 lines (83 loc) · 2.65 KB
/
mysql.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
import { Client } from "https://deno.land/x/mysql@v2.10.3/mod.ts";
var db = (conn, istx = false)=>{
return {
c: async (table, o) => {
var l = [];
var l1 = [];
var l2 = [];
var l3 = [];
for(var k in o){
if(k == 'id'){
continue;
}
l.push('??');
l1.push('?');
l2.push(k);
l3.push(o[k]);
}
var r = await conn.execute(`insert into ??(${l.join(', ')}) values(${l1.join(', ')})`, [table].concat(l2).concat(l3));
r = await conn.query(`select * from ?? where id=?`, [table, r.lastInsertId]);
return r[0];
},
u: async (table, o) => {
if(!o.id){
throw new Error('mysql.u needs object has id');
return;
}
var l = [];
var l2 = [];
l2.push(table);
for(var k in o){
if(k == 'id'){
continue;
}
l.push('??=?');
l2.push(k);
l2.push(o[k]);
}
l2.push(o.id);
await conn.execute(`update ?? set ${l.join(', ')} where id=?`, l2);
var r = await conn.query(`select * from ?? where id=?`, [table, o.id]);
if(r.length == 0){
return null;
}
return r[0];
},
r: async (table, id) => {
var r = await conn.query(`select * from ?? where id=?`, [table, id]);
if(r.length == 0){
return null;
}
return r[0];
},
d: async (table, id) => {
await conn.query(`delete from ?? where id=?`, [table, id]);
},
query: async (...args) => {
return await conn.query(...args);
},
execute: async (...args) => {
return await conn.execute(...args);
},
transaction: istx ? null : async(f)=>{
return await conn.transaction(async (conn) => {
return await f(db(conn, true));
});
},
close: async()=>{
await conn.close();
},
};
};
var mysql = async (config) => {
var dbname = config.db;
delete config.db;
var conn = await new Client().connect(config);
await conn.execute(`CREATE DATABASE IF NOT EXISTS ${dbname} charset utf8mb4 collate utf8mb4_unicode_ci`);
await conn.close();
config.db = dbname;
config.charset = "utf8mb4";
var conn = await new Client().connect(config);
return db(conn);
};
export default mysql;