Skip to content

Commit 0ff449f

Browse files
Merge branch 'main' into ESLintConfig
2 parents e41ecde + 6525b44 commit 0ff449f

File tree

3 files changed

+88
-16
lines changed

3 files changed

+88
-16
lines changed

index.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import fs from "node:fs/promises"
2+
import { existsSync } from "node:fs"
3+
import { createIfNot } from "./utils/fileUtils.mjs"
4+
import path from "node:path"
5+
async function writeSQL(statement, saveFileAs = "") {
6+
try {
7+
const destinationFile = process.argv[2] || saveFileAs
8+
if (!destinationFile) {
9+
throw new Error("Missing saveFileAs parameter")
10+
}
11+
createIfNot(path.resolve(`./sql/${destinationFile}`))
12+
await fs.writeFile(`sql/${process.argv[2]}.sql`, statement)
13+
} catch (err) {
14+
console.log(err)
15+
}
16+
}
17+
async function readCSV(csvFileName = "") {
18+
try {
19+
const fileAndTableName = process.argv[2] || csvFileName
20+
if (!fileAndTableName) {
21+
throw new Error("Missing csvFileName parameter")
22+
}
23+
if (!existsSync(path.resolve(`./csv/${fileAndTableName}.csv`))) {
24+
console.log("file not found")
25+
return
26+
}
27+
const data = await fs.readFile(`csv/${fileAndTableName}.csv`, {
28+
encoding: "utf8",
29+
})
30+
const linesArray = data.split(/\r|\n/).filter(line => line)
31+
const columnNames = linesArray.shift().split(",")
32+
let beginSQLInsert = `INSERT INTO ${fileAndTableName} (`
33+
columnNames.forEach(name => (beginSQLInsert += `${name}, `))
34+
beginSQLInsert = beginSQLInsert.slice(0, -2) + ")\nVALUES\n"
35+
let values = ""
36+
linesArray.forEach(line => {
37+
// Parses each line of CSV into field values array
38+
const arr = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/)
39+
if (arr.length > columnNames.length) {
40+
console.log(arr)
41+
throw new Error("Too Many Values in row")
42+
} else if (arr.length < columnNames.length) {
43+
console.log(arr)
44+
throw new Error("Too Few Values in row")
45+
}
46+
let valueLine = "\t("
47+
arr.forEach(value => {
48+
// Matches NULL values, Numbers,
49+
// Strings accepted as numbers, and Booleans (0 or 1)
50+
if (value === "NULL" || !isNaN(+value)) {
51+
valueLine += `${value}, `
52+
} else {
53+
// If a string is wrapped in quotes, it doesn't need more
54+
if (value.at(0) === '"') valueLine += `${value}, `
55+
else {
56+
// This wraps strings in quotes
57+
// also wraps timestamps
58+
valueLine += `"${value}", `
59+
}
60+
}
61+
})
62+
valueLine = valueLine.slice(0, -2) + "),\n"
63+
values += valueLine
64+
})
65+
values = values.slice(0, -2) + ";"
66+
const sqlStatement = beginSQLInsert + values
67+
// Write File
68+
writeSQL(sqlStatement)
69+
} catch (err) {
70+
console.log(err)
71+
}
72+
}
73+
readCSV()
74+
console.log("Finished!")

src/index.ts

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,47 @@
1-
import { promises as fs } from "fs";
2-
1+
import { promises as fs ,existsSync} from "fs";
2+
import {createIfNot} from "./utils/fileUtils.js"
3+
import * as path from "node:path"
34
async function writeSQL(statement: string, saveFileAs = "") {
45
try {
56
const destinationFile = process.argv[2] || saveFileAs;
6-
77
if (!destinationFile) {
88
throw new Error("Missing saveFileAs parameter");
99
}
10-
10+
createIfNot(path.resolve(`./sql/${destinationFile}.sql`))
1111
await fs.writeFile(`sql/${process.argv[2]}.sql`, statement);
1212
} catch (err) {
1313
console.log(err);
1414
}
1515
}
16-
1716
async function readCSV(csvFileName = "") {
1817
try {
1918
const fileAndTableName = process.argv[2] || csvFileName;
20-
2119
if (!fileAndTableName) {
2220
throw new Error("Missing csvFileName parameter");
2321
}
24-
22+
if(!existsSync(path.resolve(`./csv/${fileAndTableName}.csv`))){
23+
console.log("file not found")
24+
return
25+
}
2526
const data = await fs.readFile(`csv/${fileAndTableName}.csv`, {
2627
encoding: "utf8",
2728
});
28-
2929
const linesArray = data.split(/\r|\n/).filter((line) => line);
3030
const columnNames = linesArray?.shift()?.split(",") || [];
31-
3231
let beginSQLInsert = `INSERT INTO ${fileAndTableName} (`;
3332
columnNames.forEach((name) => (beginSQLInsert += `${name}, `));
3433
beginSQLInsert = beginSQLInsert.slice(0, -2) + ")\nVALUES\n";
35-
3634
let values = "";
3735
linesArray.forEach((line) => {
3836
// Parses each line of CSV into field values array
3937
const arr = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
40-
4138
if (arr.length > columnNames.length) {
4239
console.log(arr);
4340
throw new Error("Too Many Values in row");
4441
} else if (arr.length < columnNames.length) {
4542
console.log(arr);
4643
throw new Error("Too Few Values in row");
4744
}
48-
4945
let valueLine = "\t(";
5046
arr.forEach((value) => {
5147
// Matches NULL values, Numbers,
@@ -66,16 +62,12 @@ async function readCSV(csvFileName = "") {
6662
values += valueLine;
6763
});
6864
values = values.slice(0, -2) + ";";
69-
7065
const sqlStatement = beginSQLInsert + values;
71-
7266
// Write File
7367
writeSQL(sqlStatement);
7468
} catch (err) {
7569
console.log(err);
7670
}
7771
}
78-
7972
readCSV();
80-
8173
console.log("Finished!");

src/utils/fileUtils.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import * as fs from "node:fs"
2+
export function createIfNot(dir:string) {
3+
if (!fs.existsSync(dir)) {
4+
fs.mkdirSync(dir, { recursive: true })
5+
}
6+
}

0 commit comments

Comments
 (0)