-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupgrade-migrate.js
124 lines (106 loc) · 3.38 KB
/
upgrade-migrate.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
const rethink = require('rethinkdb');
const mysql = require('mysql');
const Promise = require('bluebird');
/**
* Config
*/
const config = {
db: 'BuckUTT_server'
};
/**
* Connection objects
*/
const sqlCon = Promise.promisifyAll(mysql.createConnection({
host : 'localhost',
user : 'root',
password: 'buckutt',
database: 'buckutt'
}));
let nosqlCon = null;
/**
* Migration functions
*/
function connectToMaria() {
return sqlCon.connectAsync()
.then(() => {
console.log('[INFO] Connected to mariadb');
});
}
function connectToRethink() {
return rethink.connect({ db: config.db })
.then((con) => {
console.log('[INFO] Connected to rethinkdb');
nosqlCon = con;
});
}
function closeSqlCon() {
return sqlCon.endAsync()
.then(() => {
console.log('[INFO] Mariadb connection closed');
});
}
function closeNosqlCon() {
return nosqlCon.close()
.then(() => {
console.log('[INFO] Rethinkdb connection closed');
});
}
function updateUserCredit() {
// Fetch and add all users
const userPromises = [];
return sqlCon.queryAsync('SELECT * FROM Users')
.then(rows => {
rows.forEach((user) => {
const credit = (user.credit) ? user.credit : 0;
userPromises.push(
rethink
.table('User')
.filter({
firstname : user.firstname,
lastname : user.lastname,
mail : user.mail
})
.filter(rethink.row('credit').ne(credit))
.update({
credit: credit
}, { returnChanges: true })
.run(nosqlCon)
.then((res) => {
if (res.replaced === 0) {
return
}
console.log(res.changes[0].new_val.firstname, res.changes[0].new_val.lastname, 'has different credit');
console.log(res.changes[0].old_val.credit, res.changes[0].new_val.credit);
const userGuid = res.changes[0].new_val.id;
return rethink
.table('Reload')
.getAll(userGuid, { index: 'Seller_id' })
.filter({
Buyer_id : userGuid,
type : 'gift',
trace : 'Transfert de l\'ancien solde BuckUTT'
})
.update({
credit
})
.run(nosqlCon);
})
);
});
})
.then(() => Promise.all(userPromises))
.then(() => console.log('[OK] Users updated '));
}
/**
* Entry point
*/
connectToMaria()
.then(connectToRethink)
.then(updateUserCredit)
.then(closeSqlCon)
.then(closeNosqlCon)
.catch(error => {
console.error(error);
console.log(`[ERR] ${error.stack}`);
return process.exit(1);
});