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