2021-12-28 15:30:07 +01:00
|
|
|
import fs from 'fs/promises';
|
|
|
|
import SqlParser from '../../../../common/libs/sqlParser';
|
|
|
|
import { BaseImporter } from '../BaseImporter';
|
|
|
|
|
|
|
|
export default class MysqlImporter extends BaseImporter {
|
|
|
|
constructor (client, options) {
|
|
|
|
super(options);
|
2022-02-24 13:14:57 +01:00
|
|
|
this._client = client;
|
2022-03-05 17:00:05 +01:00
|
|
|
this._queries = [];
|
2021-12-28 15:30:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async import () {
|
2022-03-05 17:00:05 +01:00
|
|
|
console.time('import');
|
2022-02-24 13:14:57 +01:00
|
|
|
try {
|
|
|
|
const { size: totalFileSize } = await fs.stat(this._options.file);
|
|
|
|
const parser = new SqlParser();
|
|
|
|
let readPosition = 0;
|
|
|
|
let queryCount = 0;
|
2021-12-28 15:30:07 +01:00
|
|
|
|
2022-02-24 13:14:57 +01:00
|
|
|
this.emitUpdate({
|
|
|
|
fileSize: totalFileSize,
|
|
|
|
readPosition: 0,
|
|
|
|
percentage: 0
|
2021-12-28 15:30:07 +01:00
|
|
|
});
|
|
|
|
|
2022-02-24 13:14:57 +01:00
|
|
|
await this._client.use(this._options.schema);
|
|
|
|
|
|
|
|
// 1. detect file encoding
|
|
|
|
// 2. set fh encoding
|
|
|
|
// 3. detect sql mode
|
|
|
|
// 4. restore sql mode in case of exception
|
2021-12-28 15:30:07 +01:00
|
|
|
|
2022-02-24 13:14:57 +01:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this._fileHandler.pipe(parser);
|
|
|
|
|
2022-03-05 17:00:05 +01:00
|
|
|
parser.on('error', reject);
|
2022-02-24 13:14:57 +01:00
|
|
|
|
|
|
|
parser.on('finish', () => {
|
2022-03-05 17:00:05 +01:00
|
|
|
Promise.all(this._queries)
|
|
|
|
.then(() => {
|
|
|
|
console.timeEnd('import');
|
|
|
|
console.log('TOTAL QUERIES', queryCount);
|
|
|
|
console.log('import end');
|
|
|
|
resolve();
|
|
|
|
})
|
|
|
|
.catch(reject);
|
2022-02-24 13:14:57 +01:00
|
|
|
});
|
|
|
|
|
2022-03-05 17:00:05 +01:00
|
|
|
parser.on('data', async query => {
|
|
|
|
this._queries.push(this._client.raw(query, { split: false }));
|
2022-02-24 13:14:57 +01:00
|
|
|
queryCount++;
|
2021-12-28 15:30:07 +01:00
|
|
|
});
|
|
|
|
|
2022-02-24 13:14:57 +01:00
|
|
|
this._fileHandler.on('data', (chunk) => {
|
|
|
|
readPosition += chunk.length;
|
|
|
|
this.emitUpdate({
|
|
|
|
readPosition,
|
|
|
|
percentage: readPosition / totalFileSize * 100
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
this._fileHandler.on('error', (err) => {
|
|
|
|
console.log(err);
|
|
|
|
reject(err);
|
|
|
|
});
|
2021-12-28 15:30:07 +01:00
|
|
|
});
|
2022-02-24 13:14:57 +01:00
|
|
|
}
|
|
|
|
catch (err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
2021-12-28 15:30:07 +01:00
|
|
|
}
|
|
|
|
}
|