Skip to content

Instantly share code, notes, and snippets.

@exceedsystem
Created August 24, 2021 13:05
Show Gist options
  • Save exceedsystem/767ae8564c07c36247072027a384757d to your computer and use it in GitHub Desktop.
Save exceedsystem/767ae8564c07c36247072027a384757d to your computer and use it in GitHub Desktop.
An example of 'Convert TSV to SQL Insert statement' macro for VSCodeMacros extension
// [VSCode Macros] extension
// https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros
// License:MIT
const vscode = require('vscode');
/**
* Macro configuration settings
* { [name: string]: { ... Name of the macro
* no: number, ... Order of the macro
* func: ()=> string | undefined ... Name of the body of the macro function
* }
* }
*/
module.exports.macroCommands = {
TSV2SQLInsert: {
no: 1,
func: TSV2SQLInsert,
},
};
/**
* Make SQL Insert statements from TSV
*/
async function TSV2SQLInsert() {
const editor = vscode.window.activeTextEditor;
if (!editor) {
// Return an error message if necessary.
return 'Editor is not opening.';
}
const document = editor.document;
const selection = editor.selection;
// EOL
const eol = {
1: '\n',
2: '\r\n',
}[document.eol];
// Column type array(0:text, 1:number)
const dbColumnTypes = [0, 1, 1, 0];
// Split selected lines with EOL
const tsvRows = document.getText(selection).split(eol);
let sqlRows = [];
tsvRows.forEach((row) => {
if (row.length > 0) {
// Split line
const columnValues = row.split('\t').map((s, i) => {
if (dbColumnTypes[i] === 0)
// If the value is text, Enclose it in single quotes
return `'${s}'`;
else return s;
});
const sql = `INSERT INTO XXX VALUES(${columnValues.join(',')});`;
sqlRows.push(sql);
}
});
const sqlDoc = await vscode.workspace.openTextDocument({
language: 'SQL',
content: sqlRows.join(eol),
});
await vscode.window.showTextDocument(sqlDoc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment