Skip to content

Commit 2170fed

Browse files
committed
adding log instead of throwing error
1 parent 7e6e90c commit 2170fed

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

index.js

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

0 commit comments

Comments
 (0)