This repository has been archived by the owner on Jul 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlcon.js
247 lines (221 loc) · 9.78 KB
/
sqlcon.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
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const TYPES = require('tedious').TYPES;
const mongoose = require('mongoose');
const dbConfig = require('./database');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
class SqlConnection {
constructor(options) {
// setup default config
this.config = {};
// override default config
for (let opt in options) {
if (options.hasOwnProperty(opt)) {
this.config[opt] = options[opt];
}
}
}
testServer() {
return new Promise((resolve, reject) => {
let conn = new Connection(this.config);
conn.on('errorMessage', reject);
conn.on('connect', err => {
if (err) {
reject(err);
} else {
let dbList = [];
let request = new Request('sp_databases', err => {
if (err) {
reject(err);
}
});
request.on('row', row => {
dbList.push(row[0].value);
});
request.on('doneProc', (rowCount, more) => {
resolve(dbList);
});
conn.callProcedure(request);
}
});
});
}
/**
* Count rows number of the table
*
* @param {String} table wants to count
* @param {Boolean} is_ms_shipped indicates this object was shipped or created by Microsoft
*/
tableRowsCount(table, is_ms_shipped) {
return new Promise((resolve, reject) => {
let conn = new Connection(this.config);
conn.on('errorMessage', reject);
conn.on('connect', err => {
if (err) {
return reject(err);
} else {
let query = `
SELECT SUM(rows) AS Rows
FROM sys.partitions p
LEFT JOIN sys.objects obj ON obj.object_id = p.object_id
WHERE (p.index_id in (0, 1))
AND (obj.is_ms_shipped = ${!is_ms_shipped ? 0 : 1})
AND (obj.type_desc = '${!is_ms_shipped ? 'USER_TABLE' : 'SYSTEM_TABLE'}')
AND (obj.name = '${table}')
`;
let request = new Request(query, (err, rowCount) => {
if (err) {
return reject(err);
// } else {
// console.log('rowCount: ', rowCount, query);
}
});
request.on('row', result => {
resolve(result[0].value);
});
conn.execSql(request);
}
});
});
}
transferTable(table, options) {
return new Promise((resolve, reject) => {
let lastRowId = 0;
let count = 10000;
let insertRows = 0;
let readRows = 0;
let dbConfig = this.config;
// let mongoConnection = mongoose.createConnection(options.mongodb);
let mongoConnection = mongoose.connect(options.mongodb, (err) => {
if (err) {
return reject(err);
}
// preparing data
this.tableRowsCount(table)
.then(tableRowsCount => {
console.log('tableRowsCount: ', tableRowsCount);
// start transfer
startTransfer(lastRowId, count, tableRowsCount, (err, notifyMsg) => {
if (err) {
console.error('startTransfer ERROR:', err);
reject(err);
} else {
if (notifyMsg === 'Transfer Finished!') {
resolve(tableRowsCount);
}
}
});
})
.catch(err => {
reject(err);
});
// end: connect mongoose
});
mongoose.connection.on('connected', () => {
console.log('[+] MongoDB connection established!');
});
mongoose.connection.on('error', () => {
console.log('[-] MongoDB connection error. Please make sure MongoDB is running.');
});
function startTransfer(start, count, tableRowsCount, callback) {
let task = new Promise((resolve, reject) => {
let iStart = parseInt(start);
if (iStart >= tableRowsCount) {
return resolve({
message: 'Transfer Finished!',
tableRowsCount: iStart
});
}
let query = `
DECLARE @columnName NVARCHAR(60)
SET @columnName = (SELECT TOP 1 NAME FROM sys.columns WHERE object_id = OBJECT_ID('dbo.${table}'))
SELECT * FROM (
SELECT ROW_NUMBER() OVER(ORDER BY @columnName) AS row, T.*
FROM (SELECT * FROM ${table}) T
) T2 WHERE T2.row BETWEEN ${start} AND ${start + count}
`;
let sqlcon = new Connection(dbConfig);
// console.log('start Query: ', query);
sqlcon.on('errorMessage', err => {
callback(err);
});
sqlcon.on('connect', err => {
if (err) {
console.error('$startTransfer:', err);
callback(err);
} else {
let records = [];
let schema = {};
let request = new Request(query, err => {
if (err) {
return callback(err);
}
});
request.on('columnMetadata', allColumns => {
// console.info('columnMetadata', allColumns);
if (insertRows === 0) {
// declare schema fields.
let types = require('./types');
for (let column of allColumns) {
let type = types[column.type.name];
schema[column.colName] = type;
console.info(`Cast type [${column.type.name} to ${type}]`);
}
// setup new mongodb schema
let docSchema = new Schema(schema);
mongoose.model(table, docSchema);
}
});
request.on('row', row => {
if (++readRows % 1000 == 0) {
callback(null, readRows);
}
let newRow = {};
for (let col of row) {
for (let field in schema) {
if (field === col.metadata.colName) {
newRow[field] = col.value;
break;
}
}
}
records.push(newRow);
});
request.on('doneProc', () => {
console.log('doneProc !!!!!!!!!!, readRows:', readRows);
lastRowId = lastRowId + count;
resolve(records);
});
// start sql
sqlcon.execSql(request);
}
});
});
// end: Promise
return task.then(dataRows => {
return new Promise((resolve, reject) => {
mongoose.model(table).create(dataRows)
.then(result => {
resolve(result)
})
.catch(err => {
console.error('ERROR save failed: ', err);
reject(err);
});
})
})
.then(result => {
// continue ?
// startTransfer(lastRowId, count, tableRowsCount, callback);
resolve(result);
})
.catch(err => {
callback(err);
})
}
});
}
}
// Class: SqlConnection
module.exports = SqlConnection;