Skip to content

Commit

Permalink
csvReader follows dbgate stream api
Browse files Browse the repository at this point in the history
  • Loading branch information
janproch committed Jun 11, 2020
1 parent f68bdaf commit dc7c44b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 16 deletions.
47 changes: 43 additions & 4 deletions packages/api/src/shell/csvReader.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,54 @@
const _ = require('lodash');
const csv = require('csv');
const fs = require('fs');
const stream = require('stream');

async function csvReader({ fileName, encoding = 'utf-8', ...options }) {
class CsvPrepareStream extends stream.Transform {
constructor({ header }) {
super({ objectMode: true });
this.structure = null;
this.header = header;
}
_transform(chunk, encoding, done) {
if (this.structure) {
this.push(
_.zipObject(
this.structure.columns.map((x) => x.columnName),
chunk
)
);
done();
} else {
if (this.header) {
this.structure = { columns: chunk.map((columnName) => ({ columnName })) };
this.push(this.structure);
} else {
this.structure = { columns: chunk.map((value, index) => ({ columnName: `col${index + 1}` })) };
this.push(this.structure);
this.push(
_.zipObject(
this.structure.columns.map((x) => x.columnName),
chunk
)
);
}
done();
}
}
}

async function csvReader({ fileName, encoding = 'utf-8', header = true, delimiter, quoted }) {
console.log(`Reading file ${fileName}`);
const csvStream = csv.parse({
columns: true,
...options,
// @ts-ignore
delimiter,
quoted,
});
const fileStream = fs.createReadStream(fileName, encoding);
const csvPrepare = new CsvPrepareStream({ header });
fileStream.pipe(csvStream);
return csvStream;
csvStream.pipe(csvPrepare);
return csvPrepare;
}

module.exports = csvReader;
24 changes: 12 additions & 12 deletions test/importTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@ const dbgateApi = require('@dbgate/api');
async function run() {
const csvReader = await dbgateApi.csvReader({
fileName: 'test.csv',
header: true,
// header: false,
});


const tableWriter = await dbgateApi.tableWriter({
connection: {
server: 'localhost',
engine: 'mysql',
user: 'root',
password: 'test',
port: '3307',
database: 'Chinook',
},
pureName: 'importedTable'
});
// const tableWriter = await dbgateApi.tableWriter({
// connection: {
// server: 'localhost',
// engine: 'mysql',
// user: 'root',
// password: 'test',
// port: '3307',
// database: 'Chinook',
// },
// pureName: 'importedTable'
// });

const consoleWriter = await dbgateApi.consoleObjectWriter();

Expand Down

0 comments on commit dc7c44b

Please sign in to comment.