Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatted code with most common prettier configuration. #49

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 100,
"arrowParens": "always",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"useTabs": false
}
73 changes: 38 additions & 35 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,76 @@
import { promises as fs ,existsSync} from "fs";
import {createIfNot} from "./utils/fileUtils.js"
import * as path from "node:path"
async function writeSQL(statement: string, saveFileAs = "", isAppend: boolean = false) {
import { promises as fs, existsSync } from 'fs';
import { createIfNot } from './utils/fileUtils.js';
import * as path from 'node:path';

async function writeSQL(statement: string, saveFileAs = '', isAppend: boolean = false) {
try {
const destinationFile = process.argv[2] || saveFileAs;
if (!destinationFile) {
throw new Error("Missing saveFileAs parameter");
throw new Error('Missing saveFileAs parameter');
}
createIfNot(path.resolve(`./sql/${destinationFile}.sql`))
if(isAppend){
createIfNot(path.resolve(`./sql/${destinationFile}.sql`));
if (isAppend) {
await fs.appendFile(`sql/${process.argv[2]}.sql`, statement);
}else{
} else {
await fs.writeFile(`sql/${process.argv[2]}.sql`, statement);
}
} catch (err) {
console.log(err);
}
}

async function readCSV(csvFileName = "", batchSize: number = 0) {
async function readCSV(csvFileName = '', batchSize: number = 0) {
try {
const fileAndTableName = process.argv[2] || csvFileName;

batchSize = parseInt(process.argv[3]) || batchSize || 500;
let isAppend: boolean = false;
let isAppend: boolean = false;

if (!fileAndTableName) {
throw new Error("Missing csvFileName parameter");
throw new Error('Missing csvFileName parameter');
}
if(!existsSync(path.resolve(`./csv/${fileAndTableName}.csv`))){
console.log("file not found")
return
if (!existsSync(path.resolve(`./csv/${fileAndTableName}.csv`))) {
console.log('file not found');
return;
}
const data = await fs.readFile(`csv/${fileAndTableName}.csv`, {
encoding: "utf8",
encoding: 'utf8',
});
const linesArray = data.split(/\r|\n/).filter((line) => line);
const columnNames = linesArray?.shift()?.split(",") || [];
let beginSQLInsert = `INSERT INTO ${fileAndTableName} (`;
columnNames.forEach((name) => (beginSQLInsert += `${name}, `));
beginSQLInsert = beginSQLInsert.slice(0, -2) + ")\nVALUES\n";
let values = "";
const columnNames = linesArray?.shift()?.split(',') || [];

// Improved string manipulation using array join
const beginSQLInsert = `INSERT INTO ${fileAndTableName} (${columnNames.join(', ')})\nVALUES\n`;

let values = '';
linesArray.forEach((line, index) => {
// Parses each line of CSV into field values array
const arr = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
if (arr.length > columnNames.length) {
console.log(arr);
throw new Error("Too Many Values in row");
throw new Error('Too Many Values in row');
} else if (arr.length < columnNames.length) {
console.log(arr);
throw new Error("Too Few Values in row");
throw new Error('Too Few Values in row');
}

// Check batch size (rows per batch)
if(index > 0 && index % batchSize == 0){
values = values.slice(0, -2) + ";\n\n";
if (index > 0 && index % batchSize == 0) {
values = values.slice(0, -2) + ';\n\n';

const sqlStatement = beginSQLInsert + values;
// Write File

// Write File
writeSQL(sqlStatement, fileAndTableName, isAppend);
values = "";
values = '';
isAppend = true;
}
let valueLine = "\t(";

let valueLine = '\t(';
arr.forEach((value) => {
// Matches NULL values, Numbers,
// Strings accepted as numbers, and Booleans (0 or 1)
if (value === "NULL" || !isNaN(+value)) {
if (value === 'NULL' || !isNaN(+value)) {
valueLine += `${value}, `;
} else {
// If a string is wrapped in quotes, it doesn't need more
Expand All @@ -80,16 +82,17 @@ async function readCSV(csvFileName = "", batchSize: number = 0) {
}
}
});
valueLine = valueLine.slice(0, -2) + "),\n";
valueLine = valueLine.slice(0, -2) + '),\n';
values += valueLine;
});
values = values.slice(0, -2) + ";";
values = values.slice(0, -2) + ';';
const sqlStatement = beginSQLInsert + values;
// Write File
writeSQL(sqlStatement, fileAndTableName, isAppend);
} catch (err) {
console.log(err);
}
}

readCSV();
console.log("Finished!");
console.log('Finished!');
6 changes: 3 additions & 3 deletions src/utils/fileUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as fs from "node:fs"
export function createIfNot(dir:string) {
import * as fs from 'node:fs';
export function createIfNot(dir: string) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
fs.mkdirSync(dir, { recursive: true });
}
}